Time a function

From Rosetta Code
Revision as of 02:45, 24 December 2011 by rosettacode>Crazyfirex (→‎{{header|AutoHotkey}}: add QueryPerformanceCounter version)
Task
Time a function
You are encouraged to solve this task according to the task description, using any language you may know.

Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute.

Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer.

This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.

Ada

<lang ada>with Ada.Calendar; use Ada.Calendar; with Ada.Text_Io; use Ada.Text_Io;

procedure Query_Performance is

  type Proc_Access is access procedure(X : in out Integer);
  function Time_It(Action : Proc_Access; Arg : Integer) return Duration is
     Start_Time : Time := Clock;
     Finis_Time : Time;
     Func_Arg : Integer := Arg;
  begin
     Action(Func_Arg);
     Finis_Time := Clock;
     return Finis_Time - Start_Time;
  end Time_It;
  procedure Identity(X : in out Integer) is
  begin
     X := X;
  end Identity;
  procedure Sum (Num : in out Integer) is
  begin
     for I in 1..1000 loop
        Num := Num + I;
     end loop;
  end Sum;
  Id_Access : Proc_Access := Identity'access;
  Sum_Access : Proc_Access := Sum'access;
  

begin

  Put_Line("Identity(4) takes" & Duration'Image(Time_It(Id_Access, 4)) & " seconds.");
  Put_Line("Sum(4) takes:" & Duration'Image(Time_It(Sum_Access, 4)) & " seconds.");

end Query_Performance;</lang>

Example

Identity(4) takes 0.000001117 seconds.
Sum(4) takes: 0.000003632 seconds.

Aime

<lang aime>integer identity(integer x) {

   return x;

}


integer sum(integer c) {

   integer s;
   s = 0;
   while (c) {

s += c; c -= 1;

   }
   return s;

}


real time_f(integer (*fp) (integer), integer fa) {

   date f, s;
   time t;
   d_now(s);
   fp(fa);
   d_now(f);
   t_ddiff(t, f, s);
   return t_microsecond(t) / 1000000r;

}


integer main(void) {

   o_real(6, time_f(identity, 1));
   o_text(" seconds\n");
   o_real(6, time_f(sum, 1000000));
   o_text(" seconds\n");
   return 0;

}</lang>

AutoHotkey

System time

Uses system time, not process time <lang AutoHotkey>MsgBox % time("fx") Return

fx() {

 Sleep, 1000

}

time(function, parameter=0) {

 SetBatchLines -1  ; don't sleep for other green threads
 StartTime := A_TickCount
 %function%(parameter)
 Return ElapsedTime := A_TickCount - StartTime . " milliseconds"

}</lang>

Using QueryPerformanceCounter

QueryPerformanceCounter allows even more precision: <lang AHK>MsgBox % time("fx")

time(function, parameter=0){ SetBatchLines -1 DllCall("QueryPerformanceCounter", "Int64*", CounterBefore) DllCall("QueryPerformanceFrequency", "Int64*", Freq) %function%(parameter) DllCall("QueryPerformanceCounter", "Int64*", CounterAfter) return (CounterAfter-CounterBefore)/Freq * 1000 " milliseconds" }

fx(){ Sleep 1000 }</lang>

BASIC

Works with: QBasic

<lang qbasic>DIM timestart AS SINGLE, timedone AS SINGLE, timeelapsed AS SINGLE

timestart = TIMER SLEEP 1 'code or function to execute goes here timedone = TIMER

'midnight check: IF timedone < timestart THEN timedone = timedone + 86400 timeelapsed = timedone - timestart</lang>

See also: BBC BASIC, PureBasic.

BBC BASIC

<lang bbcbasic>start%=TIME:REM centi-second timer REM perform processing lapsed%=TIME-start%</lang>

C

Works with: POSIX version .1-2001

On some system (like GNU/Linux) to be able to use the clock_gettime function you must link with the rt (RealTime) library.

<lang c>#include <stdio.h>

  1. include <time.h>

int identity(int x) { return x; }

int sum(int s) {

 int i;
 for(i=0; i < 1000000; i++) s += i;
 return s;

}

  1. define CLOCKTYPE CLOCK_MONOTONIC

/* this one should be appropriate to avoid errors on multiprocessors systems */

double time_it(int (*action)(int), int arg) {

 struct timespec tsi, tsf;
 clock_gettime(CLOCKTYPE, &tsi);
 action(arg);
 clock_gettime(CLOCKTYPE, &tsf);
 double elaps_s = difftime(tsf.tv_sec, tsi.tv_sec);
 long elaps_ns = tsf.tv_nsec - tsi.tv_nsec;
 return elaps_s + ((double)elaps_ns) / 1.0e9;

}

int main() {

 printf("identity (4) takes %lf s\n", time_it(identity, 4));
 printf("sum      (4) takes %lf s\n", time_it(sum, 4));
 return 0;

}</lang>

C++

<lang cpp>#include <ctime>

  1. include <iostream>

using namespace std;

int identity(int x) { return x; } int sum(int num) {

 for (int i = 0; i < 1000000; i++)
   num += i;
 return num;

}

double time_it(int (*action)(int), int arg) {

 clock_t start_time = clock();
 action(arg);
 clock_t finis_time = clock();
 return ((double) (finis_time - start_time)) / CLOCKS_PER_SEC;

}

int main() {

 cout << "Identity(4) takes " << time_it(identity, 4) << " seconds." << endl;
 cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl;
 return 0;

}</lang>

Example

Identity(4) takes 0 seconds.
Sum(4) takes 0.01 seconds.

C#

Using Stopwatch.

<lang csharp>using System; using System.Linq; using System.Threading; using System.Diagnostics;

class Program {

   static void Main(string[] args) {
       Stopwatch sw = new Stopwatch();
       sw.Start();
       DoSomething();
       sw.Stop();
       Console.WriteLine("DoSomething() took {0}ms.", sw.Elapsed.TotalMilliseconds);
   }
   static void DoSomething() {
       Thread.Sleep(1000);
       Enumerable.Range(1, 10000).Where(x => x % 2 == 0).Sum();  // Sum even numers from 1 to 10000
   }

}</lang>

Using DateTime.

<lang csharp>using System; using System.Linq; using System.Threading;

class Program {

   static void Main(string[] args) {
       DateTime start, end;
       start = DateTime.Now;
       DoSomething();
       end = DateTime.Now;
       Console.WriteLine("DoSomething() took " + (end - start).TotalMilliseconds + "ms");
   }    
   static void DoSomething() {
       Thread.Sleep(1000);
       Enumerable.Range(1, 10000).Where(x => x % 2 == 0).Sum();  // Sum even numers from 1 to 10000
   }

}</lang>

Output:

DoSomething() took 1071,5408ms

Clojure

<lang clojure>

 (defn fib []
   (map first 
     (iterate 
       (fn a b [b (+ a b)])
       [0 1])))
 (time (take 100 (fib)))

</lang>

Output:

"Elapsed time: 0.028 msecs"
(0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181)

Common Lisp

Common Lisp provides a standard utility for performance measurement, time:

<lang lisp>CL-USER> (time (reduce #'+ (make-list 100000 :initial-element 1))) Evaluation took:

 0.151 seconds of real time
 0.019035 seconds of user run time
 0.01807 seconds of system run time
 0 calls to %EVAL
 0 page faults and
 2,400,256 bytes consed.</lang>

(The example output here is from SBCL.)

However, it merely prints textual information to trace output, so the information is not readily available for further processing (except by parsing it in a CL-implementation-specific manner).

The functions get-internal-run-time and get-internal-real-time may be used to get time information programmatically, with at least one-second granularity (and usually more). Here is a function which uses them to measure the time taken for one execution of a provided function:

<lang lisp>(defun timings (function)

 (let ((real-base (get-internal-real-time))
       (run-base (get-internal-run-time)))
   (funcall function)
   (values (/ (- (get-internal-real-time) real-base) internal-time-units-per-second)
           (/ (- (get-internal-run-time) run-base) internal-time-units-per-second))))

CL-USER> (timings (lambda () (reduce #'+ (make-list 100000 :initial-element 1)))) 17/500 7/250</lang>

D

<lang d>import std.stdio, std.datetime;

int identity(int x) {

   return x;

}

int sum(int num) {

   foreach (i; 0 .. 100_000_000)
       num += i;
   return num;

}

double timeIt(int function(int) func, int arg) {

   StopWatch sw;
   sw.start();
   func(arg);
   sw.stop();
   return sw.peek().usecs / 1_000_000.0;

}

void main() {

   writefln("identity(4) takes %f6 seconds.", timeIt(&identity, 4));
   writefln("sum(4) takes %f seconds.", timeIt(&sum, 4));

}</lang>

Output:

identity(4) takes 0.0000016 seconds.
sum(4) takes 0.522065 seconds.

Using Tango

<lang d> import tango.io.Stdout; import tango.time.Clock;

int identity (int x) {

   return x;

}

int sum (int num) {

   for (int i = 0; i < 1000000; i++)
     num += i;
   return num;

}

double timeIt(int function(int) func, int arg) {

   long before = Clock.now.ticks;
   func(arg);
   return (Clock.now.ticks - before) / cast(double)TimeSpan.TicksPerSecond;

}

void main () {

   Stdout.format("Identity(4) takes {:f6} seconds",timeIt(&identity,4)).newline;
   Stdout.format("Sum(4) takes {:f6} seconds",timeIt(&sum,4)).newline;

} </lang>

E

Translation of: Java

— E has no standardized facility for CPU time measurement; this

Works with: E-on-Java

.

<lang e>def countTo(x) { println("Counting...") for _ in 1..x {} println("Done!") }

def MX := <unsafe:java.lang.management.makeManagementFactory> def threadMX := MX.getThreadMXBean() require(threadMX.isCurrentThreadCpuTimeSupported()) threadMX.setThreadCpuTimeEnabled(true)

for count in [10000, 100000] { def start := threadMX.getCurrentThreadCpuTime() countTo(count) def finish := threadMX.getCurrentThreadCpuTime() println(`Counting to $count takes ${(finish-start)//1000000}ms`) }</lang>

Euphoria

<lang euphoria>atom t t = time() some_procedure() t = time() - t printf(1,"Elapsed %f seconds.\n",t)</lang>

F#

The .Net framework provides a Stopwatch class which provides a performance counter. <lang fsharp> open System.Diagnostics let myfunc data =

   let timer = new Stopwatch()
   timer.Start()
   let result = data |> expensive_processing
   timer.Stop()
   printf "elapsed %d ms" timer.ElapsedMilliseconds
   result

</lang>

Factor

<lang factor>[ 10000 iota sum drop ] time</lang> Output:

Running time: 0.002888635 seconds

Additional information was collected.
dispatch-stats.  - Print method dispatch statistics
gc-events.       - Print all garbage collection events
gc-stats.        - Print breakdown of different garbage collection events
gc-summary.      - Print aggregate garbage collection statistics

Forth

Works with: GNU Forth

<lang forth>: time: ( "word" -- )

 utime 2>R ' EXECUTE
 utime 2R> D-
 <# # # # # # # [CHAR] . HOLD #S #> TYPE ."  seconds" ;

1000 time: MS \ 1.000081 seconds ok</lang>

Fortran

Works with: Gfortran

version 4.4.5 (Debian 4.4.5-8) on x86_64-linux-gnu

<lang fortran> c The subroutine to analyze

     subroutine do_something()

c For testing we just do nothing for 3 seconds

     call sleep(3)
     return
     end

c Main Program

     program timing
     integer(kind=8) start,finish,rate,max
     call system_clock(start,rate,max)         

c Here comes the function we want to time

     call do_something()
     call system_clock(finish,rate,max)         
     write(6,*) 'Elapsed Time in seconds:',(finish-start)/rate
     return
     end

</lang>

GAP

<lang gap># Return the time passed in last function time;</lang>

Go

Gotest

Go has a standard command for benchmarking, gotest, which can time a function. Given a package with functions, <lang go>package empty

func Empty() {}

func Count() {

   // count to a million
   for i := 0; i < 1e6; i++ {
   }

}</lang> the following code will time them: <lang go>package empty

import "testing"

func BenchmarkEmpty(b *testing.B) {

   for i := 0; i < b.N; i++ {
       Empty()
   }

}

func BenchmarkCount(b *testing.B) {

   for i := 0; i < b.N; i++ {
       Count()
   }

}</lang> Gotest varies b.N to get meaningful resolution. Example:

$ gotest -bench=".+"
rm -f _test/pal.a
8g  -o _gotest_.8 empty.go empty_test.go
rm -f _test/pal.a
gopack grc _test/pal.a _gotest_.8 
testing: warning: no tests to run
PASS
empty.BenchmarkEmpty	100000000	        14 ns/op
empty.BenchmarkCount	    1000	   1002840 ns/op

Gotest is the preferred technique when you wish to communicate results to other Go programmers because the output format and benchmarking technique will be known to them.

Alternative technique

Very simplistic. As the first line of the function you wish to time, use defer with an argument of time.Now() to print the elapsed time to the return of any function. For example, define the function from as shown below. It works because defer evaluates its function's arguments at the time the function is deferred, so the current time gets captured at the point of the defer. When the function containing the defer returns, the deferred from function runs, computes the elapsed time as a time.Duration, and prints it with standard formatting, which adds a nicely scaled unit suffix. <lang go>package main

import (

   "fmt"
   "time"

)

func from(t0 time.Time) {

   fmt.Println(time.Now().Sub(t0))

}

func empty() {

   defer from(time.Now())

}

func count() {

   defer from(time.Now())
   for i := 0; i < 1e6; i++ {
   }

}

func main() {

   empty()
   count()

}</lang> Output:

2us
643us

Haskell

<lang haskell>import System.CPUTime

-- We assume the function we are timing is an IO monad computation timeIt :: (Fractional c) => (a -> IO b) -> a -> IO c timeIt action arg =

 do startTime <- getCPUTime
    action arg
    finishTime <- getCPUTime
    return $ fromIntegral (finishTime - startTime) / 1000000000000

-- Version for use with evaluating regular non-monadic functions timeIt' :: (Fractional c) => (a -> b) -> a -> IO c timeIt' f = timeIt (\x -> f x `seq` return ())</lang>

Example

*Main> :m + Text.Printf Data.List
*Main Data.List Text.Printf> timeIt' id 4 >>= printf "Identity(4) takes %f seconds.\n"
Identity(4) takes 0.0 seconds.
*Main Data.List Text.Printf> timeIt' (\x -> foldl' (+) x [1..1000000]) 4 >>= printf "Sum(4) takes %f seconds.\n"
Sum(4) takes 0.248015 seconds.

HicEst

<lang HicEst>t_start = TIME()  ! returns seconds since midnight SYSTEM(WAIT = 1234) ! wait 1234 milliseconds t_end = TIME()

WRITE(StatusBar) t_end - t_start, " seconds"</lang>

Icon and Unicon

The function 'timef' takes as argument a procedure name and collects performance and timing information including run time (in milliseconds), garbage collection, and memory usage by region.

<lang Icon>procedure timef(f) #: time a function f local gcol,alloc,used,size,runtime,header,x,i

title := ["","total","static","string","block"] # headings collect() # start with collected memory (before baseline) every put(gcol  := [], -&collections) # baseline collections count every put(alloc := [], -&allocated) # . total allocated space by region every put(used  := [], -&storage) # . currently used space by region - no total every put(size  := [], -&regions) # . current size of regions - no total

write("Performance and Timing measurement for ",image(f),":") runtime := &time # base time f() write("Execution time=",&time-runtime," ms.")

every (i := 0, x := &collections) do gcol[i +:= 1] +:= x every (i := 0, x := &allocated ) do alloc[i +:= 1] +:= x every (i := 0, x := &storage ) do used[i +:= 1] +:= x every (i := 0, x := &regions ) do size[i +:= 1] +:= x

push(gcol,"garbage collections:") push(alloc,"memory allocated:") push(used,"N/A","currently used:") push(size,"N/A","current size:")

write("Memory Region and Garbage Collection Summary (delta):") every (i := 0) <:= *!(title|gcol|alloc|used|size) every x := (title|gcol|alloc|used|size) do {

  f := left
  every writes(f(!x,i + 3)) do f := right
  write()
  }

write("Note: static region values should be zero and may not be meaningful.") return end</lang>

Sample usage:<lang Icon>procedure main() timef(perfectnumbers) end

procedure perfectnumbers() ...</lang>

Sample output (from the Perfect Numbers task):

Performance and Timing measurement for procedure perfectnumbers:
Perfect numbers from 1 to 10000:
6
28
496
8128
Done.
Execution time=416 ms.
Memory Region and Garbage Collection Summary (delta):
                                         total                 static                 string                  block
garbage collections:                         2                      0                      0                      2
memory allocated:                      1247012                      0                     24                1246988
currently used:                            N/A                      0                      0                 248040
current size:                              N/A                      0                      0                      0
Note: static region values should be zero and may not be meaningful.

Ioke

<lang ioke>use("benchmark")

func = method((1..50000) reduce(+))

Benchmark report(1, 1, func)</lang>

J

Time and space requirements are tested using verbs obtained through the Foreign conjunction (!:). 6!:2 returns time required for execution, in floating-point measurement of seconds. 7!:2 returns a measurement of space required to execute. Both receive as input a sentence for execution.
When the Memoize feature or similar techniques are used, execution time and space can both be affected by prior calculations.

Example

<lang j> (6!:2,7!:2) '|: 50 50 50 $ i. 50^3' 0.00387912 1.57414e6</lang>

Java

Works with: Java version 1.5+

<lang java>import java.lang.management.ManagementFactory; import java.lang.management.ThreadMXBean;

public class TimeIt { public static void main(String[] args) { final ThreadMXBean threadMX = ManagementFactory.getThreadMXBean(); assert threadMX.isCurrentThreadCpuTimeSupported(); threadMX.setThreadCpuTimeEnabled(true);

long start, end; start = threadMX.getCurrentThreadCpuTime(); countTo(100000000); end = threadMX.getCurrentThreadCpuTime(); System.out.println("Counting to 100000000 takes "+(end-start)/1000000+"ms"); start = threadMX.getCurrentThreadCpuTime(); countTo(1000000000L); end = threadMX.getCurrentThreadCpuTime(); System.out.println("Counting to 1000000000 takes "+(end-start)/1000000+"ms");

}

public static void countTo(long x){ System.out.println("Counting..."); for(long i=0;i<x;i++); System.out.println("Done!"); } }</lang>

Measures real time rather than CPU time:

Works with: Java version (all versions)

<lang java> public static void main(String[] args){ long start, end; start = System.currentTimeMillis(); countTo(100000000); end = System.currentTimeMillis(); System.out.println("Counting to 100000000 takes "+(end-start)+"ms"); start = System.currentTimeMillis(); countTo(1000000000L); end = System.currentTimeMillis(); System.out.println("Counting to 1000000000 takes "+(end-start)+"ms");

}</lang> Output:

Counting...
Done!
Counting to 100000000 takes 370ms
Counting...
Done!
Counting to 1000000000 takes 3391ms

Works with: UCB Logo

on a Unix system

This is not an ideal method; Logo does not expose a timer (except for the WAIT command) so we use the Unix "date" command to get a second timer.

<lang logo>to time

 output first first shell "|date +%s|

end to elapsed :block

 localmake "start time
 run :block
 (print time - :start [seconds elapsed])

end

elapsed [wait 300]  ; 5 seconds elapsed</lang>

Lua

<lang lua>function Test_Function()

   for i = 1, 10000000 do
       local s = math.log( i )
       s = math.sqrt( s )
   end

end

t1 = os.clock()

   Test_Function()

t2 = os.clock()

print( os.difftime( t2, t1 ) )</lang>

Mathematica

<lang Mathematica>AbsoluteTiming[x];</lang> where x is an operation. Example calculating a million digits of Sqrt[3]: <lang Mathematica>AbsoluteTiming[N[Sqrt[3], 10^6]]</lang> gives: <lang Mathematica>{0.000657, 1.7320508075688772935274463......}</lang> First elements if the time in seconds, second elements if the result from the operation. Note that I truncated the result.

OCaml

<lang ocaml>let time_it action arg =

 let start_time = Sys.time () in
 ignore (action arg);
 let finish_time = Sys.time () in
 finish_time -. start_time</lang>

Example

# Printf.printf "Identity(4) takes %f seconds.\n" (time_it (fun x -> x) 4);;
Identity(4) takes 0.000000 seconds.
- : unit = ()
# let sum x = let num = ref x in for i = 0 to 999999 do num := !num + i done; !num;;
val sum : int -> int = <fun>
# Printf.printf "Sum(4) takes %f seconds.\n" (time_it sum 4);;
Sum(4) takes 0.084005 seconds.
- : unit = ()

Oz

<lang oz>declare

 %% returns milliseconds
 fun {TimeIt Proc}
    Before = {Now}
 in
    {Proc}
    {Now} - Before
 end
 fun {Now}
    {Property.get 'time.total'}
 end

in

 {Show
  {TimeIt
   proc {$}
      {FoldL {List.number 1 1000000 1} Number.'+' 4 _}
   end}
 }</lang>

PARI/GP

This version, by default, returns just the time used by Pari, not the delta of wall times. Pari can be compiled to use wall time if you prefer. <lang parigp>time(foo)={

 foo();
 gettime()

};</lang>

Perl

Example of using the built-in Benchmark core module - it compares two versions of recursive factorial functions: <lang perl>use Benchmark; use Memoize;

sub fac1 {

   my $n = shift;
   return $n == 0 ? 1 : $n * fac1($n - 1);

} sub fac2 {

   my $n = shift;
   return $n == 0 ? 1 : $n * fac2($n - 1);

} memoize('fac2');

my $result = timethese(100000, {

   'fac1' => sub { fac1(50) },
   'fac2' => sub { fac2(50) },

}); Benchmark::cmpthese($result);</lang> Output:

Benchmark: timing 100000 iterations of fac1, fac2...
      fac1:  6 wallclock secs ( 5.45 usr +  0.00 sys =  5.45 CPU) @ 18348.62/s (n=100000)
      fac2:  1 wallclock secs ( 0.84 usr +  0.00 sys =  0.84 CPU) @ 119047.62/s (n=100000)
         Rate fac1 fac2
fac1  18349/s   -- -85%
fac2 119048/s 549%   --

Example without using Benchmark: <lang perl>sub cpu_time {

 my ($user,$system,$cuser,$csystem) = times;
 $user + $system

}

sub time_it {

 my $action = shift;
 my $startTime = cpu_time();
 $action->(@_);
 my $finishTime = cpu_time();
 $finishTime - $startTime

}

printf "Identity(4) takes %f seconds.\n", time_it(sub {@_}, 4);

  1. outputs "Identity(4) takes 0.000000 seconds."

sub sum {

 my $x = shift;
 foreach (0 .. 999999) {
   $x += $_;
 }
 $x

}

printf "Sum(4) takes %f seconds.\n", time_it(\&sum, 4);

  1. outputs "Sum(4) takes 0.280000 seconds."</lang>

PicoLisp

There is a built-in function 'bench' for that. However, it measures wall-clock time, because for practical purposes the real time needed by a task (including I/O and communication) is more meaningful. There is another function, 'tick', which also measures user time, and is used by the profiling tools. <lang PicoLisp>: (bench (do 1000000 (* 3 4))) 0.080 sec -> 12</lang>

PL/I

<lang PL/I>declare (start_time, finish_time) float (18);

start_time = secs();

do i = 1 to 10000000;

  /* something to be repeated goes here. */

end; finish_time = secs();

put skip edit ('elapsed time=', finish_time - start_time, ' seconds')

  (A, F(10,3), A);
  /* gives the result to thousandths of a second. */

/* Note: using the SECS function takes into account the clock */ /* going past midnight. */</lang>

PureBasic

Built in timer

This version uses the built in timer, on Windows it has an accuracy of ~10-15 msec. <lang Purebasic>Procedure Foo(Limit)

 Protected i, palindromic, String$
 For i=0 To Limit
   String$=Str(i)
   If String$=ReverseString(String$)
     palindromic+1
   EndIf
 Next
 ProcedureReturn palindromic

EndProcedure

If OpenConsole()

 Define Start, Stop, cnt
 PrintN("Starting timing of a calculation,")
 PrintN("for this we test how many of 0-1000000 are palindromic.")
 Start=ElapsedMilliseconds()
 cnt=Foo(1000000)
 Stop=ElapsedMilliseconds()
 PrintN("The function need "+Str(stop-Start)+" msec,")
 PrintN("and "+Str(cnt)+" are palindromic.")
 Print("Press ENTER to exit."): Input()

EndIf</lang>

Starting timing of a calculation,
for this we test how many of 0-1000000 are palindromic.
The function need 577 msec,
and 1999 are palindromic.
Press ENTER to exit.

Hi-res version

Library: Droopy

This version uses a hi-res timer, but it is Windows only. <lang PureBasic>If OpenConsole()

 Define Timed.f, cnt
 PrintN("Starting timing of a calculation,")
 PrintN("for this we test how many of 0-1000000 are palindromic.")
 ; Dependent on Droopy-library
 If MeasureHiResIntervalStart()
   ; Same Foo() as above...
   cnt=Foo(1000000)
   Timed=MeasureHiResIntervalStop()
 EndIf
 PrintN("The function need "+StrF(Timed*1000,3)+" msec,")
 PrintN("and "+Str(cnt)+" are palindromic.")
 Print("Press ENTER to exit."): Input()

EndIf</lang>

Starting timing of a calculation,
for this we test how many of 0-1000000 are palindromic.
The function need 604.341 msec,
and 1999 are palindromic.
Press ENTER to exit.

This version still relies on the Windows API but does not make use of any additional libraries. <lang PureBasic>Procedure.f ticksHQ(reportIfPresent = #False)

 Static maxfreq.q 
 Protected T.q 
 If reportIfPresent Or maxfreq = 0 
   QueryPerformanceFrequency_(@maxfreq) 
   If maxfreq
     ProcedureReturn 1.0
   Else
     ProcedureReturn 0
   EndIf 
 EndIf 
 QueryPerformanceCounter_(@T) 
 ProcedureReturn T / maxfreq ;Result is in milliseconds

EndProcedure

If OpenConsole()

 Define timed.f, cnt
 PrintN("Starting timing of a calculation,")
 PrintN("for this we test how many of 0-1000000 are palindromic.")
 ; Dependent on Windows API
 If ticksHQ(#True)
   timed = ticksHQ() ;start time
   ; Same Foo() as above...
   cnt = Foo(1000000)
   timed = ticksHQ() - timed ;difference
 EndIf
 PrintN("The function need " + StrF(timed * 1000, 3) + " msec,")
 PrintN("and " + Str(cnt) + " are palindromic.")
 Print("Press ENTER to exit."): Input()

EndIf</lang>

Sample output:

Starting timing of a calculation,
for this we test how many of 0-1000000 are palindromic.
The function need 174.811 msec,
and 1999 are palindromic.

Python

Given function and arguments return a time (in microseconds) it takes to make the call.

Note: There is an overhead in executing a function that does nothing. <lang python>import sys, timeit def usec(function, arguments):

   modname, funcname = __name__, function.__name__
   timer = timeit.Timer(stmt='%(funcname)s(*args)' % vars(),
                        setup='from %(modname)s import %(funcname)s; args=%(arguments)r' % vars())
   try:
       t, N = 0, 1
       while t < 0.2:            
           t = min(timer.repeat(repeat=3, number=N))            
           N *= 10
       microseconds = round(10000000 * t / N, 1) # per loop
       return microseconds 
   except:
       timer.print_exc(file=sys.stderr)
       raise
def nothing(): pass
def identity(x): return x</lang>

Example

>>> print usec(nothing, [])
1.7
>>> print usec(identity, [1])
2.2
>>> print usec(pow, (2, 100))
3.3
>>> print [usec(qsort, (range(n),)) for n in range(10)]
[2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]

using qsort() from Quicksort. Timings show that the implementation of qsort() has quadratic dependence on sequence length N for already sorted sequences (instead of O(N*log(N)) in average).

R

R has a built-in function, system.time, to calculate this. <lang R># A task foo <- function() {

  for(i in 1:10)
  {
     mat <- matrix(rnorm(1e6), nrow=1e3)
     mat^-0.5
  }

}

  1. Time the task

timer <- system.time(foo())

  1. Extract the processing time

timer["user.self"]</lang> For a breakdown of processing time by function, there is Rprof. <lang R>Rprof() foo() Rprof(NULL) summaryRprof()</lang>

Retro

Retro has a time function returning the current time in seconds. This can be used to build a simple timing function:

<lang Retro>: .runtime ( a- ) time [ do time ] dip - "\n%d\n" puts ;

test 20000 [ putn space ] iterd ;

&test .runtime</lang>

Finer measurements are not possible with the standard implementation.

REXX

REXX doesn't have a language feature for true CPU time, but it does have a built-in function for elapsed time(s). <lang rexx> /*REXX program to show the elapsed time for a function. */

call time 'E' call silly say 'function SILLY took' format(time("E"),,2) 'seconds.'

        /* The above  2  for the FORMAT function displays the time */
        /* with 2 decimal digits (past the decimal point).   Using */
        /* a  0  (zero)  would round the time to whole seconds.    */

exit


silly: procedure /*subroutine chews up CPU time doing silly stuff*/

 do j=1 for 100000
 a.j=random() date() time() digits() fuzz() form() xrange() queued()
 end

return </lang> Output:

function SILLY took 3.54 seconds.

Ruby

Ruby's Benchmark module provides a way to generate nice reports (numbers are in seconds): <lang ruby>require 'benchmark'

Benchmark.bm(8) do |x|

 x.report("nothing:")  {  }
 x.report("sum:")  { (1..1_000_000).inject(4) {|sum, x| sum + x} }

end</lang> Output:

              user     system      total        real
nothing:  0.000000   0.000000   0.000000 (  0.000014)
sum:      2.700000   0.400000   3.100000 (  3.258348)

You can get the total time as a number for later processing like this: <lang ruby>Benchmark.measure { whatever }.total</lang>

Scala

Define a time function that returns the elapsed time (in ms) to execute a block of code. <lang scala> def time(f: => Unit)={ val s = System.currentTimeMillis f System.currentTimeMillis - s } </lang> Can be called with a code block: <lang scala> println(time { for(i <- 1 to 10000000) {} }) </lang> Or with a function: <lang scala> def count(i:Int) = for(j <- 1 to i){}

println(time (count(10000000))) </lang>

Scheme

<lang scheme>(time (some-function))</lang>

Seed7

<lang seed7>$ include "seed7_05.s7i";

 include "time.s7i";
 include "duration.s7i";

const func integer: identity (in integer: x) is

 return x;

const func integer: sum (in integer: num) is func

 result
   var integer: result is 0;
 local
   var integer: number is 0;
 begin
   result := num;
   for number range 1 to 1000000 do
     result +:= number;
   end for;
 end func;

const func duration: timeIt (ref func integer: aFunction) is func

 result
   var duration: result is duration.value;
 local
   var time: before is time.value;
 begin
   before := time(NOW);
   ignore(aFunction);
   result := time(NOW) - before;
 end func;

const proc: main is func

 begin
   writeln("Identity(4) takes " <& timeIt(identity(4)));
   writeln("Sum(4)      takes " <& timeIt(sum(4)));
 end func;</lang>

Output of interpreted program:

Identity(4) takes 0-00-00 00:00:00.000163
Sum(4)      takes 0-00-00 00:00:00.131823

Output of compiled program (optimized with -O2):

Identity(4) takes 0-00-00 00:00:00.000072
Sum(4)      takes 0-00-00 00:00:00.000857

Slate

<lang slate> [inform: 2000 factorial] timeToRun. </lang>

Smalltalk

(Squeak/Pharo) <lang smalltalk> Time millisecondsToRun: [ Transcript show: 2000 factorial ]. </lang>

Standard ML

<lang sml>fun time_it (action, arg) = let

 val timer = Timer.startCPUTimer ()
 val _ = action arg
 val times = Timer.checkCPUTimer timer

in

 Time.+ (#usr times, #sys times)

end</lang>

Example

- print ("Identity(4) takes " ^ Time.toString (time_it (fn x => x, 4)) ^ " seconds.\n");
Identity(4) takes 0.000 seconds.
val it = () : unit
- fun sum (x:IntInf.int) = let
    fun loop (i, sum) =
      if i >= 1000000 then sum
      else loop (i + 1, sum + i)
  in loop (0, x)
  end;
val sum = fn : IntInf.int -> IntInf.int
- print ("Sum(4) takes " ^ Time.toString (time_it (sum, 4)) ^ " seconds.\n");
Sum(4) takes 0.220 seconds.
val it = () : unit

Tcl

The Tcl time command returns the real time elapsed averaged over a number of iterations. <lang tcl>proc sum_n {n} {

   for {set i 1; set sum 0.0} {$i <= $n} {incr i} {set sum [expr {$sum + $i}]}
   return [expr {wide($sum)}]

}

puts [time {sum_n 1e6} 100] puts [time {} 100]</lang> Results in

163551.0 microseconds per iteration
0.2 microseconds per iteration

TUSCRIPT

<lang tuscript> $$ MODE TUSCRIPT SECTION test LOOP n=1,999999 rest=MOD (n,1000) IF (rest==0) Print n ENDLOOP ENDSECTION time_beg=TIME () DO test time_end=TIME () interval=TIME_INTERVAL (seconds,time_beg,time_end) PRINT "'test' start at ",time_beg PRINT "'test' ends at ",time_end PRINT "'test' takes ",interval," seconds" </lang> Output:

'test' start at 2011-01-15 14:38:22
'test' ends  at 2011-01-15 14:38:31
'test' takes 9 seconds

UNIX Shell

<lang bash>$ time sleep 1</lang>

real    0m1.074s
user    0m0.001s
sys     0m0.006s