Time a function: Difference between revisions

Content added Content deleted
(add BQN)
m (syntax highlighting fixup automation)
Line 20: Line 20:
{{trans|Nim}}
{{trans|Nim}}


<lang 11l>F do_work(x)
<syntaxhighlight lang="11l">F do_work(x)
V n = x
V n = x
L(i) 10000000
L(i) 10000000
Line 31: Line 31:
R time:perf_counter() - start
R time:perf_counter() - start


print(time_func(() -> do_work(100)))</lang>
print(time_func(() -> do_work(100)))</syntaxhighlight>


=={{header|8051 Assembly}}==
=={{header|8051 Assembly}}==
Line 47: Line 47:
is (256^x - 1) * 2^(-p).
is (256^x - 1) * 2^(-p).


<lang asm>TC EQU 8 ; number of counter registers
<syntaxhighlight lang="asm">TC EQU 8 ; number of counter registers
TSTART EQU 08h ; first register of timer counter
TSTART EQU 08h ; first register of timer counter
TEND EQU TSTART + TC - 1 ; end register of timer counter
TEND EQU TSTART + TC - 1 ; end register of timer counter
Line 152: Line 152:


END
END
</syntaxhighlight>
</lang>


=={{header|ACL2}}==
=={{header|ACL2}}==


<lang Lisp>(time$ (nthcdr 9999999 (take 10000000 nil)))</lang>
<syntaxhighlight lang="lisp">(time$ (nthcdr 9999999 (take 10000000 nil)))</syntaxhighlight>


Output (for Clozure):
Output (for Clozure):
Line 165: Line 165:


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>BYTE RTCLOK1=$13
<syntaxhighlight lang="action!">BYTE RTCLOK1=$13
BYTE RTCLOK2=$14
BYTE RTCLOK2=$14
BYTE PALNTSC=$D014
BYTE PALNTSC=$D014
Line 208: Line 208:
PrintF("%U ms%E",diffMs)
PrintF("%U ms%E",diffMs)
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Time_a_function.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Time_a_function.png Screenshot from Atari 8-bit computer]
Line 221: Line 221:


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with Ada.Calendar; use Ada.Calendar;
<syntaxhighlight lang="ada">with Ada.Calendar; use Ada.Calendar;
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Text_Io; use Ada.Text_Io;


Line 251: Line 251:
Put_Line("Identity(4) takes" & Duration'Image(Time_It(Id_Access, 4)) & " seconds.");
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.");
Put_Line("Sum(4) takes:" & Duration'Image(Time_It(Sum_Access, 4)) & " seconds.");
end Query_Performance;</lang>
end Query_Performance;</syntaxhighlight>
===Example===
===Example===
Identity(4) takes 0.000001117 seconds.
Identity(4) takes 0.000001117 seconds.
Line 257: Line 257:


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>integer
<syntaxhighlight lang="aime">integer
identity(integer x)
identity(integer x)
{
{
Line 306: Line 306:


0;
0;
}</lang>
}</syntaxhighlight>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program fcttime.s */
/* program fcttime.s */
Line 540: Line 540:
pop {r2-r4}
pop {r2-r4}
bx lr @ return
bx lr @ return
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 572: Line 572:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>benchmark [
<syntaxhighlight lang="rebol">benchmark [
print "starting function"
print "starting function"
pause 2000
pause 2000
print "function ended"
print "function ended"
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 587: Line 587:
===System time===
===System time===
Uses system time, not process time
Uses system time, not process time
<lang AutoHotkey>MsgBox % time("fx")
<syntaxhighlight lang="autohotkey">MsgBox % time("fx")
Return
Return


Line 601: Line 601:
%function%(parameter)
%function%(parameter)
Return ElapsedTime := A_TickCount - StartTime . " milliseconds"
Return ElapsedTime := A_TickCount - StartTime . " milliseconds"
}</lang>
}</syntaxhighlight>
=== Using QueryPerformanceCounter ===
=== Using QueryPerformanceCounter ===
QueryPerformanceCounter allows even more precision:
QueryPerformanceCounter allows even more precision:
<lang AHK>MsgBox, % TimeFunction("fx")
<syntaxhighlight lang="ahk">MsgBox, % TimeFunction("fx")


TimeFunction(Function, Parameters*) {
TimeFunction(Function, Parameters*) {
Line 619: Line 619:
fx() {
fx() {
Sleep, 1000
Sleep, 1000
}</lang>
}</syntaxhighlight>


=={{header|BaCon}}==
=={{header|BaCon}}==
The BaCon '''TIMER''' function keeps track of time spent running, in milliseconds (which is also the time unit used by '''SLEEP'''). This is not process specific, but a wall clock time counter which starts at 0 during process initialization. As BaCon can easily use external C libraries, process specific ''CLOCK_PROCESS_CPUTIME_ID'' '''clock_gettime''' could also be used.
The BaCon '''TIMER''' function keeps track of time spent running, in milliseconds (which is also the time unit used by '''SLEEP'''). This is not process specific, but a wall clock time counter which starts at 0 during process initialization. As BaCon can easily use external C libraries, process specific ''CLOCK_PROCESS_CPUTIME_ID'' '''clock_gettime''' could also be used.


<lang freebasic>' Time a function
<syntaxhighlight lang="freebasic">' Time a function
SUB timed()
SUB timed()
SLEEP 7000
SLEEP 7000
Line 632: Line 632:
timed()
timed()
et = TIMER
et = TIMER
PRINT st, ", ", et</lang>
PRINT st, ", ", et</syntaxhighlight>


{{out}}
{{out}}
Line 640: Line 640:
=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|QBasic}}
{{works with|QBasic}}
<lang qbasic>DIM timestart AS SINGLE, timedone AS SINGLE, timeelapsed AS SINGLE
<syntaxhighlight lang="qbasic">DIM timestart AS SINGLE, timedone AS SINGLE, timeelapsed AS SINGLE


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


See also: [[#BBC BASIC|BBC BASIC]], [[#PureBasic|PureBasic]].
See also: [[#BBC BASIC|BBC BASIC]], [[#PureBasic|PureBasic]].


=={{header|BASIC256}}==
=={{header|BASIC256}}==
<lang BASIC256>call cont(10000000)
<syntaxhighlight lang="basic256">call cont(10000000)
print msec; " milliseconds"
print msec; " milliseconds"


Line 666: Line 666:
sum += 1
sum += 1
next i
next i
end subroutine</lang>
end subroutine</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
Granularity: hundredths of second.
Granularity: hundredths of second.
<syntaxhighlight lang="batch file">
<lang Batch File>
@echo off
@echo off
Setlocal EnableDelayedExpansion
Setlocal EnableDelayedExpansion
Line 693: Line 693:
)
)
goto:eof
goto:eof
</syntaxhighlight>
</lang>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic>start%=TIME:REM centi-second timer
<syntaxhighlight lang="bbcbasic">start%=TIME:REM centi-second timer
REM perform processing
REM perform processing
lapsed%=TIME-start%</lang>
lapsed%=TIME-start%</syntaxhighlight>


=={{header|BQN}}==
=={{header|BQN}}==
To execute a function <code>F</code> once and get the amount of time it took to execute with value <code>v</code>, you can do this:
To execute a function <code>F</code> once and get the amount of time it took to execute with value <code>v</code>, you can do this:
<lang bqn>F •_timed v</lang>
<syntaxhighlight lang="bqn">F •_timed v</syntaxhighlight>
<code>•_timed</code> is a system value that runs <code>F</code> a set number of times and returns the average runtime of the function. Here, since the left argument <code>𝕨</code> is omitted, it is run once.
<code>•_timed</code> is a system value that runs <code>F</code> a set number of times and returns the average runtime of the function. Here, since the left argument <code>𝕨</code> is omitted, it is run once.


Line 708: Line 708:


Here are a few example runs:
Here are a few example runs:
<lang bqn> {0:1;𝕩×𝕊𝕩-1}•_timed 100
<syntaxhighlight lang="bqn"> {0:1;𝕩×𝕊𝕩-1}•_timed 100
8.437800000000001e¯05
8.437800000000001e¯05
{0:1;𝕩×𝕊𝕩-1}•_timed 1000
{0:1;𝕩×𝕊𝕩-1}•_timed 1000
0.000299545</lang>
0.000299545</syntaxhighlight>




=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>( ( time
<syntaxhighlight lang="bracmat">( ( time
= fun funarg t0 ret
= fun funarg t0 ret
. !arg:(?fun.?funarg)
. !arg:(?fun.?funarg)
Line 728: Line 728:
)
)
& time$(fib.30)
& time$(fib.30)
)</lang>
)</syntaxhighlight>
Output:
Output:
<pre>1346269.5,141*10E0 s</pre>
<pre>1346269.5,141*10E0 s</pre>
Line 738: Line 738:
<code>CLOCK_PROCESS_CPUTIME_ID</code> is preferred when available (eg. Linux kernel 2.6.12 up), being CPU time used by the current process. (<code>CLOCK_MONOTONIC</code> generally includes CPU time of unrelated processes, and may be drifted by <code>adjtime()</code>.)
<code>CLOCK_PROCESS_CPUTIME_ID</code> is preferred when available (eg. Linux kernel 2.6.12 up), being CPU time used by the current process. (<code>CLOCK_MONOTONIC</code> generally includes CPU time of unrelated processes, and may be drifted by <code>adjtime()</code>.)


<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <time.h>
#include <time.h>


Line 776: Line 776:
printf("sum (4) takes %lf s\n", time_it(sum, 4));
printf("sum (4) takes %lf s\n", time_it(sum, 4));
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
Line 782: Line 782:
Using Stopwatch.
Using Stopwatch.


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Linq;
using System.Threading;
using System.Threading;
Line 803: Line 803:
Enumerable.Range(1, 10000).Where(x => x % 2 == 0).Sum(); // Sum even numers from 1 to 10000
Enumerable.Range(1, 10000).Where(x => x % 2 == 0).Sum(); // Sum even numers from 1 to 10000
}
}
}</lang>
}</syntaxhighlight>


Using DateTime.
Using DateTime.


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Linq;
using System.Threading;
using System.Threading;
Line 827: Line 827:
Enumerable.Range(1, 10000).Where(x => x % 2 == 0).Sum(); // Sum even numers from 1 to 10000
Enumerable.Range(1, 10000).Where(x => x % 2 == 0).Sum(); // Sum even numers from 1 to 10000
}
}
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 833: Line 833:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <ctime>
<syntaxhighlight lang="cpp">#include <ctime>
#include <iostream>
#include <iostream>
using namespace std;
using namespace std;
Line 855: Line 855:
cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl;
cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl;
return 0;
return 0;
}</lang>
}</syntaxhighlight>


===Example===
===Example===
Line 862: Line 862:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>
<syntaxhighlight lang="clojure">
(defn fib []
(defn fib []
(map first
(map first
Line 870: Line 870:


(time (take 100 (fib)))
(time (take 100 (fib)))
</syntaxhighlight>
</lang>


Output:
Output:
Line 880: Line 880:
Common Lisp provides a standard utility for performance measurement, [http://www.lispworks.com/documentation/HyperSpec/Body/m_time.htm time]:
Common Lisp provides a standard utility for performance measurement, [http://www.lispworks.com/documentation/HyperSpec/Body/m_time.htm time]:


<lang lisp>CL-USER> (time (reduce #'+ (make-list 100000 :initial-element 1)))
<syntaxhighlight lang="lisp">CL-USER> (time (reduce #'+ (make-list 100000 :initial-element 1)))
Evaluation took:
Evaluation took:
0.151 seconds of real time
0.151 seconds of real time
Line 887: Line 887:
0 calls to %EVAL
0 calls to %EVAL
0 page faults and
0 page faults and
2,400,256 bytes consed.</lang>
2,400,256 bytes consed.</syntaxhighlight>


(The example output here is from [[SBCL]].)
(The example output here is from [[SBCL]].)
Line 895: Line 895:
The functions [http://www.lispworks.com/documentation/HyperSpec/Body/f_get__1.htm get-internal-run-time] and [http://www.lispworks.com/documentation/HyperSpec/Body/f_get_in.htm 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:
The functions [http://www.lispworks.com/documentation/HyperSpec/Body/f_get__1.htm get-internal-run-time] and [http://www.lispworks.com/documentation/HyperSpec/Body/f_get_in.htm 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)
<syntaxhighlight lang="lisp">(defun timings (function)
(let ((real-base (get-internal-real-time))
(let ((real-base (get-internal-real-time))
(run-base (get-internal-run-time)))
(run-base (get-internal-run-time)))
Line 904: Line 904:
CL-USER> (timings (lambda () (reduce #'+ (make-list 100000 :initial-element 1))))
CL-USER> (timings (lambda () (reduce #'+ (make-list 100000 :initial-element 1))))
17/500
17/500
7/250</lang>
7/250</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.datetime;
<syntaxhighlight lang="d">import std.stdio, std.datetime;


int identity(int x) {
int identity(int x) {
Line 930: Line 930:
writefln("identity(4) takes %f6 seconds.", timeIt(&identity, 4));
writefln("identity(4) takes %f6 seconds.", timeIt(&identity, 4));
writefln("sum(4) takes %f seconds.", timeIt(&sum, 4));
writefln("sum(4) takes %f seconds.", timeIt(&sum, 4));
}</lang>
}</syntaxhighlight>
Output:<pre>identity(4) takes 0.0000016 seconds.
Output:<pre>identity(4) takes 0.0000016 seconds.
sum(4) takes 0.522065 seconds.</pre>
sum(4) takes 0.522065 seconds.</pre>
===Using Tango===
===Using Tango===
<syntaxhighlight lang="d">
<lang d>
import tango.io.Stdout;
import tango.io.Stdout;
import tango.time.Clock;
import tango.time.Clock;
Line 962: Line 962:
Stdout.format("Sum(4) takes {:f6} seconds",timeIt(&sum,4)).newline;
Stdout.format("Sum(4) takes {:f6} seconds",timeIt(&sum,4)).newline;
}
}
</syntaxhighlight>
</lang>


=={{header|E}}==
=={{header|E}}==
Line 968: Line 968:
{{trans|Java}} — E has no ''standardized'' facility for CPU time measurement; this {{works with|E-on-Java}}.
{{trans|Java}} — E has no ''standardized'' facility for CPU time measurement; this {{works with|E-on-Java}}.


<lang e>def countTo(x) {
<syntaxhighlight lang="e">def countTo(x) {
println("Counting...")
println("Counting...")
for _ in 1..x {}
for _ in 1..x {}
Line 984: Line 984:
def finish := threadMX.getCurrentThreadCpuTime()
def finish := threadMX.getCurrentThreadCpuTime()
println(`Counting to $count takes ${(finish-start)//1000000}ms`)
println(`Counting to $count takes ${(finish-start)//1000000}ms`)
}</lang>
}</syntaxhighlight>


=={{header|Elena}}==
=={{header|Elena}}==
{{trans|C#}}
{{trans|C#}}
ELENA 4.x :
ELENA 4.x :
<lang elena>import system'calendar;
<syntaxhighlight lang="elena">import system'calendar;
import system'routines;
import system'routines;
import system'threading;
import system'threading;
Line 1,011: Line 1,011:
console.printLine("Time elapsed in msec:",(end - start).Milliseconds)
console.printLine("Time elapsed in msec:",(end - start).Milliseconds)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,020: Line 1,020:
{{trans|Erlang}}
{{trans|Erlang}}
'''tc/1'''
'''tc/1'''
<lang elixir>iex(10)> :timer.tc(fn -> Enum.each(1..100000, fn x -> x*x end) end)
<syntaxhighlight lang="elixir">iex(10)> :timer.tc(fn -> Enum.each(1..100000, fn x -> x*x end) end)
{236000, :ok}</lang>
{236000, :ok}</syntaxhighlight>
'''tc/2'''
'''tc/2'''
<lang elixir>iex(11)> :timer.tc(fn x -> Enum.each(1..x, fn y -> y*y end) end, [1000000])
<syntaxhighlight lang="elixir">iex(11)> :timer.tc(fn x -> Enum.each(1..x, fn y -> y*y end) end, [1000000])
{2300000, :ok}</lang>
{2300000, :ok}</syntaxhighlight>
'''tc/3'''
'''tc/3'''
<lang elixir>iex(12)> :timer.tc(Enum, :to_list, [1..1000000])
<syntaxhighlight lang="elixir">iex(12)> :timer.tc(Enum, :to_list, [1..1000000])
{224000,
{224000,
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 46, 47, 48, 49, ...]}</lang>
42, 43, 44, 45, 46, 47, 48, 49, ...]}</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
Line 1,036: Line 1,036:


'''tc/1''' takes a 0-arity function and executes it:
'''tc/1''' takes a 0-arity function and executes it:
<lang erlang>
<syntaxhighlight lang="erlang">
5> {Time,Result} = timer:tc(fun () -> lists:foreach(fun(X) -> X*X end, lists:seq(1,100000)) end).
5> {Time,Result} = timer:tc(fun () -> lists:foreach(fun(X) -> X*X end, lists:seq(1,100000)) end).
{226391,ok}
{226391,ok}
Line 1,042: Line 1,042:
0.226391
0.226391
7> % Time is in microseconds.
7> % Time is in microseconds.
</syntaxhighlight>
</lang>
'''tc/2''' takes an n-arity function and its arguments:
'''tc/2''' takes an n-arity function and its arguments:
<lang erlang>
<syntaxhighlight lang="erlang">
9> timer:tc(fun (X) -> lists:foreach(fun(Y) -> Y*Y end, lists:seq(1,X)) end, [1000000]).
9> timer:tc(fun (X) -> lists:foreach(fun(Y) -> Y*Y end, lists:seq(1,X)) end, [1000000]).
{2293844,ok}
{2293844,ok}
</syntaxhighlight>
</lang>
'''tc/3''' takes a module name, function name and the list of arguments to the function:
'''tc/3''' takes a module name, function name and the list of arguments to the function:
<lang erlang>
<syntaxhighlight lang="erlang">
8> timer:tc(lists,seq,[1,1000000]).
8> timer:tc(lists,seq,[1,1000000]).
{62370,
{62370,
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,
23,24,25,26,27|...]}
23,24,25,26,27|...]}
</syntaxhighlight>
</lang>


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


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
The .Net framework provides a Stopwatch class which provides a performance counter.
The .Net framework provides a Stopwatch class which provides a performance counter.
<lang fsharp>
<syntaxhighlight lang="fsharp">
open System.Diagnostics
open System.Diagnostics
let myfunc data =
let myfunc data =
Line 1,074: Line 1,074:
printf "elapsed %d ms" timer.ElapsedMilliseconds
printf "elapsed %d ms" timer.ElapsedMilliseconds
result
result
</syntaxhighlight>
</lang>


=={{header|Factor}}==
=={{header|Factor}}==
{{works with|Factor|0.98}}
{{works with|Factor|0.98}}
<lang factor>USING: kernel sequences tools.time ;
<syntaxhighlight lang="factor">USING: kernel sequences tools.time ;


[ 10000 <iota> sum drop ] time</lang>
[ 10000 <iota> sum drop ] time</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,094: Line 1,094:
=={{header|Forth}}==
=={{header|Forth}}==
{{works with|GNU Forth}}
{{works with|GNU Forth}}
<lang forth>: time: ( "word" -- )
<syntaxhighlight lang="forth">: time: ( "word" -- )
utime 2>R ' EXECUTE
utime 2>R ' EXECUTE
utime 2R> D-
utime 2R> D-
<# # # # # # # [CHAR] . HOLD #S #> TYPE ." seconds" ;
<# # # # # # # [CHAR] . HOLD #S #> TYPE ." seconds" ;


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


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Gfortran}} version 4.4.5 (Debian 4.4.5-8) on x86_64-linux-gnu
{{works with|Gfortran}} version 4.4.5 (Debian 4.4.5-8) on x86_64-linux-gnu


<lang fortran>
<syntaxhighlight lang="fortran">
c The subroutine to analyze
c The subroutine to analyze
subroutine do_something()
subroutine do_something()
Line 1,123: Line 1,123:
return
return
end
end
</syntaxhighlight>
</lang>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Function sumToLimit(limit As UInteger) As UInteger
Function sumToLimit(limit As UInteger) As UInteger
Line 1,144: Line 1,144:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,153: Line 1,153:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap># Return the time passed in last function
<syntaxhighlight lang="gap"># Return the time passed in last function
time;</lang>
time;</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
Line 1,160: Line 1,160:
The Go command line tool <code>go test</code> includes [http://golang.org/pkg/testing/#hdr-Benchmarks benchmarking support].
The Go command line tool <code>go test</code> includes [http://golang.org/pkg/testing/#hdr-Benchmarks benchmarking support].
Given a package with functions:
Given a package with functions:
<lang go>package empty
<syntaxhighlight lang="go">package empty


func Empty() {}
func Empty() {}
Line 1,168: Line 1,168:
for i := 0; i < 1e6; i++ {
for i := 0; i < 1e6; i++ {
}
}
}</lang>
}</syntaxhighlight>
the following code, placed in a file whose name ends in <tt>_test.go</tt>, will time them:
the following code, placed in a file whose name ends in <tt>_test.go</tt>, will time them:
<lang go>package empty
<syntaxhighlight lang="go">package empty


import "testing"
import "testing"
Line 1,184: Line 1,184:
Count()
Count()
}
}
}</lang>
}</syntaxhighlight>
<code>go test</code> varies <code>b.N</code> to get meaningful resolution.
<code>go test</code> varies <code>b.N</code> to get meaningful resolution.
Example:
Example:
Line 1,202: Line 1,202:
===testing.Benchmark===
===testing.Benchmark===
The benchmarking features of the <code>testing</code> package are exported for use within a Go program.
The benchmarking features of the <code>testing</code> package are exported for use within a Go program.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,232: Line 1,232:
fmt.Printf("Empty: %12.4f\n", float64(e.T.Nanoseconds())/float64(e.N))
fmt.Printf("Empty: %12.4f\n", float64(e.T.Nanoseconds())/float64(e.N))
fmt.Printf("Count: %12.4f\n", float64(c.T.Nanoseconds())/float64(c.N))
fmt.Printf("Count: %12.4f\n", float64(c.T.Nanoseconds())/float64(c.N))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,246: Line 1,246:


As the first line of the function you wish to time, use <tt>defer</tt> with an argument of <tt>time.Now()</tt> to print the elapsed time to the return of any function. For example, define the function <tt>from</tt> 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 <tt>from</tt> function runs, computes the elapsed time as a <tt>time.Duration</tt>, and prints it with standard formatting, which adds a nicely scaled unit suffix.
As the first line of the function you wish to time, use <tt>defer</tt> with an argument of <tt>time.Now()</tt> to print the elapsed time to the return of any function. For example, define the function <tt>from</tt> 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 <tt>from</tt> function runs, computes the elapsed time as a <tt>time.Duration</tt>, and prints it with standard formatting, which adds a nicely scaled unit suffix.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,270: Line 1,270:
empty()
empty()
count()
count()
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,280: Line 1,280:
{{trans|Java}}
{{trans|Java}}
===CPU Timing===
===CPU Timing===
<lang groovy>import java.lang.management.ManagementFactory
<syntaxhighlight lang="groovy">import java.lang.management.ManagementFactory
import java.lang.management.ThreadMXBean
import java.lang.management.ThreadMXBean


Line 1,291: Line 1,291:
c.call()
c.call()
(threadMX.currentThreadCpuTime - start)/1000000
(threadMX.currentThreadCpuTime - start)/1000000
}</lang>
}</syntaxhighlight>


===Wall Clock Timing===
===Wall Clock Timing===
<lang groovy>def clockRealTime = { Closure c ->
<syntaxhighlight lang="groovy">def clockRealTime = { Closure c ->
def start = System.currentTimeMillis()
def start = System.currentTimeMillis()
c.call()
c.call()
System.currentTimeMillis() - start
System.currentTimeMillis() - start
}</lang>
}</syntaxhighlight>


Test:
Test:
<lang groovy>def countTo = { Long n ->
<syntaxhighlight lang="groovy">def countTo = { Long n ->
long i = 0; while(i < n) { i += 1L }
long i = 0; while(i < n) { i += 1L }
}
}
Line 1,311: Line 1,311:
println "Counting to ${testSize} takes ${measuredTime}ms of ${measurementType}"
println "Counting to ${testSize} takes ${measuredTime}ms of ${measurementType}"
}
}
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 1,322: Line 1,322:


=={{header|Halon}}==
=={{header|Halon}}==
<lang halon>$t = uptime();
<syntaxhighlight lang="halon">$t = uptime();


sleep(1);
sleep(1);


echo uptime() - $t;</lang>
echo uptime() - $t;</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import System.CPUTime (getCPUTime)
<syntaxhighlight lang="haskell">import System.CPUTime (getCPUTime)


-- We assume the function we are timing is an IO monad computation
-- We assume the function we are timing is an IO monad computation
Line 1,341: Line 1,341:
-- Version for use with evaluating regular non-monadic functions
-- Version for use with evaluating regular non-monadic functions
timeIt_ :: (Fractional c) => (a -> b) -> a -> IO c
timeIt_ :: (Fractional c) => (a -> b) -> a -> IO c
timeIt_ f = timeIt ((`seq` return ()) . f)</lang>
timeIt_ f = timeIt ((`seq` return ()) . f)</syntaxhighlight>


===Example===
===Example===
Line 1,351: Line 1,351:


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang HicEst>t_start = TIME() ! returns seconds since midnight
<syntaxhighlight lang="hicest">t_start = TIME() ! returns seconds since midnight
SYSTEM(WAIT = 1234) ! wait 1234 milliseconds
SYSTEM(WAIT = 1234) ! wait 1234 milliseconds
t_end = TIME()
t_end = TIME()


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


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|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.
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
<syntaxhighlight lang="icon">procedure timef(f) #: time a function f
local gcol,alloc,used,size,runtime,header,x,i
local gcol,alloc,used,size,runtime,header,x,i


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


Sample usage:<lang Icon>procedure main()
Sample usage:<syntaxhighlight lang="icon">procedure main()
timef(perfectnumbers)
timef(perfectnumbers)
end
end


procedure perfectnumbers()
procedure perfectnumbers()
...</lang>
...</syntaxhighlight>


Sample output (from the [[Perfect_numbers#Icon_and_Unicon|Perfect Numbers]] task):
Sample output (from the [[Perfect_numbers#Icon_and_Unicon|Perfect Numbers]] task):
Line 1,421: Line 1,421:


=={{header|Ioke}}==
=={{header|Ioke}}==
<lang ioke>use("benchmark")
<syntaxhighlight lang="ioke">use("benchmark")


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


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


=={{header|J}}==
=={{header|J}}==
Line 1,431: Line 1,431:
<br>When the [http://www.jsoftware.com/help/dictionary/dmcapdot.htm Memoize] feature or similar techniques are used, execution time and space can both be affected by prior calculations.
<br>When the [http://www.jsoftware.com/help/dictionary/dmcapdot.htm Memoize] feature or similar techniques are used, execution time and space can both be affected by prior calculations.
===Example===
===Example===
<lang j> (6!:2 , 7!:2) '|: 50 50 50 $ i. 50^3'
<syntaxhighlight lang="j"> (6!:2 , 7!:2) '|: 50 50 50 $ i. 50^3'
0.00488008 3.14829e6
0.00488008 3.14829e6
timespacex '|: 50 50 50 $ i. 50^3'
timespacex '|: 50 50 50 $ i. 50^3'
0.00388519 3.14829e6</lang>
0.00388519 3.14829e6</syntaxhighlight>
=={{header|Janet}}==
=={{header|Janet}}==
<lang Clojure>(defmacro time
<syntaxhighlight lang="clojure">(defmacro time
"Print the time it takes to evaluate body to stderr.\n
"Print the time it takes to evaluate body to stderr.\n
Evaluates to body."
Evaluates to body."
Line 1,446: Line 1,446:
,$val)))
,$val)))


(time (os/sleep 0.5))</lang>
(time (os/sleep 0.5))</syntaxhighlight>
{{out}}
{{out}}
<pre>0.500129</pre>
<pre>0.500129</pre>
Line 1,452: Line 1,452:
=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<lang java>import java.lang.management.ManagementFactory;
<syntaxhighlight lang="java">import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.lang.management.ThreadMXBean;


Line 1,478: Line 1,478:
System.out.println("Done!");
System.out.println("Done!");
}
}
}</lang>
}</syntaxhighlight>


Measures real time rather than CPU time:
Measures real time rather than CPU time:
{{works with|Java|(all versions)}}
{{works with|Java|(all versions)}}


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


}</lang>
}</syntaxhighlight>
Output:
Output:
Counting...
Counting...
Line 1,504: Line 1,504:


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang javascript>
<syntaxhighlight lang="javascript">
function test() {
function test() {
let n = 0
let n = 0
Line 1,517: Line 1,517:


console.log('test() took ' + ((end - start) / 1000) + ' seconds') // test() took 0.001 seconds
console.log('test() took ' + ((end - start) / 1000) + ' seconds') // test() took 0.001 seconds
</syntaxhighlight>
</lang>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia># v0.6.0
<syntaxhighlight lang="julia"># v0.6.0


function countto(n::Integer)
function countto(n::Integer)
Line 1,532: Line 1,532:


@time countto(10 ^ 5)
@time countto(10 ^ 5)
@time countto(10 ^ 10)</lang>
@time countto(10 ^ 10)</syntaxhighlight>


{{out}}
{{out}}
Line 1,546: Line 1,546:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Java}}
{{trans|Java}}
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2
// need to enable runtime assertions with JVM -ea option
// need to enable runtime assertions with JVM -ea option


Line 1,569: Line 1,569:
println("Counting to $count takes ${(end-start)/1000000}ms")
println("Counting to $count takes ${(end-start)/1000000}ms")
}
}
}</lang>
}</syntaxhighlight>
This is a typical result (sometimes the second figure is only about 1400ms - no idea why)
This is a typical result (sometimes the second figure is only about 1400ms - no idea why)
{{out}}
{{out}}
Line 1,582: Line 1,582:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>local(start = micros)
<syntaxhighlight lang="lasso">local(start = micros)
loop(100000) => {
loop(100000) => {
'nothing is outout because no autocollect'
'nothing is outout because no autocollect'
}
}
'time for 100,000 loop repititions: '+(micros - #start)+' microseconds'</lang>
'time for 100,000 loop repititions: '+(micros - #start)+' microseconds'</syntaxhighlight>


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>on testFunc ()
<syntaxhighlight lang="lingo">on testFunc ()
repeat with i = 1 to 1000000
repeat with i = 1 to 1000000
x = sqrt(log(i))
x = sqrt(log(i))
end repeat
end repeat
end</lang>
end</syntaxhighlight>


<lang lingo>ms = _system.milliseconds
<syntaxhighlight lang="lingo">ms = _system.milliseconds
testFunc()
testFunc()
ms = _system.milliseconds - ms
ms = _system.milliseconds - ms
put "Execution time in ms:" && ms
put "Execution time in ms:" && ms
-- "Execution time in ms: 983"</lang>
-- "Execution time in ms: 983"</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
Line 1,606: Line 1,606:
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.
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
<syntaxhighlight lang="logo">to time
output first first shell "|date +%s|
output first first shell "|date +%s|
end
end
Line 1,615: Line 1,615:
end
end


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


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function Test_Function()
<syntaxhighlight lang="lua">function Test_Function()
for i = 1, 10000000 do
for i = 1, 10000000 do
local s = math.log( i )
local s = math.log( i )
Line 1,629: Line 1,629:
t2 = os.clock()
t2 = os.clock()


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


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Line 1,647: Line 1,647:
10000 is Double (default)
10000 is Double (default)


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module Checkit {
Module sumtolimit (limit) {
Module sumtolimit (limit) {
Line 1,676: Line 1,676:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
The built-in command CodeTools:-Usage can compute the "real" time for the length of the computation or the "cpu" time for the computation. The following examples find the real time and cpu time for computing the integer factors for 32!+1.
The built-in command CodeTools:-Usage can compute the "real" time for the length of the computation or the "cpu" time for the computation. The following examples find the real time and cpu time for computing the integer factors for 32!+1.
<lang maple>CodeTools:-Usage(ifactor(32!+1), output = realtime, quiet);</lang>
<syntaxhighlight lang="maple">CodeTools:-Usage(ifactor(32!+1), output = realtime, quiet);</syntaxhighlight>
<lang maple>CodeTools:-Usage(ifactor(32!+1), output = cputime, quiet);</lang>
<syntaxhighlight lang="maple">CodeTools:-Usage(ifactor(32!+1), output = cputime, quiet);</syntaxhighlight>


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


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>f(n) := if n < 2 then n else f(n - 1) + f(n - 2)$
<syntaxhighlight lang="maxima">f(n) := if n < 2 then n else f(n - 1) + f(n - 2)$


/* First solution, call the time function with an output line number, it gives the time taken to compute that line.
/* First solution, call the time function with an output line number, it gives the time taken to compute that line.
Line 1,707: Line 1,707:
f(24);
f(24);
Evaluation took 0.9400 seconds (0.9400 elapsed)
Evaluation took 0.9400 seconds (0.9400 elapsed)
46368</lang>
46368</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>start = time
<syntaxhighlight lang="miniscript">start = time
for i in range(1,100000)
for i in range(1,100000)
end for
end for
duration = time - start
duration = time - start
print "Process took " + duration + " seconds"</lang>
print "Process took " + duration + " seconds"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,721: Line 1,721:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import times, strutils
<syntaxhighlight lang="nim">import times, strutils
proc doWork(x: int) =
proc doWork(x: int) =
Line 1,733: Line 1,733:
cpuTime() - t0
cpuTime() - t0
echo "Time = ", time(doWork(100)).formatFloat(ffDecimal, precision = 3), " s"</lang>
echo "Time = ", time(doWork(100)).formatFloat(ffDecimal, precision = 3), " s"</syntaxhighlight>


{{out}}
{{out}}
Line 1,740: Line 1,740:


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let time_it action arg =
<syntaxhighlight lang="ocaml">let time_it action arg =
let start_time = Sys.time () in
let start_time = Sys.time () in
ignore (action arg);
ignore (action arg);
let finish_time = Sys.time () in
let finish_time = Sys.time () in
finish_time -. start_time</lang>
finish_time -. start_time</syntaxhighlight>


===Example===
===Example===
Line 1,772: Line 1,772:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
%% returns milliseconds
%% returns milliseconds
fun {TimeIt Proc}
fun {TimeIt Proc}
Line 1,790: Line 1,790:
{FoldL {List.number 1 1000000 1} Number.'+' 4 _}
{FoldL {List.number 1 1000000 1} Number.'+' 4 _}
end}
end}
}</lang>
}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
This version, by default, returns just the CPU time used by gp, not the delta of wall times. PARI can be compiled to use wall time if you prefer: configure with <code>--time=ftime</code> instead of <code>--time=
This version, by default, returns just the CPU time used by gp, not the delta of wall times. PARI can be compiled to use wall time if you prefer: configure with <code>--time=ftime</code> instead of <code>--time=
getrusage</code>, <code>--time=clock_gettime</code>, or <code>--time=times</code>. See Appendix A, section 2.2 of the User's Guide to PARI/GP.
getrusage</code>, <code>--time=clock_gettime</code>, or <code>--time=times</code>. See Appendix A, section 2.2 of the User's Guide to PARI/GP.
<lang parigp>time(foo)={
<syntaxhighlight lang="parigp">time(foo)={
foo();
foo();
gettime();
gettime();
}</lang>
}</syntaxhighlight>


Alternate version:
Alternate version:
{{works with|PARI/GP|2.6.2+}}
{{works with|PARI/GP|2.6.2+}}
<lang parigp>time(foo)={
<syntaxhighlight lang="parigp">time(foo)={
my(start=getabstime());
my(start=getabstime());
foo();
foo();
getabstime()-start;
getabstime()-start;
}</lang>
}</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
Example of using the built-in Benchmark core module - it compares two versions of recursive factorial functions:
Example of using the built-in Benchmark core module - it compares two versions of recursive factorial functions:
<lang perl>use Benchmark;
<syntaxhighlight lang="perl">use Benchmark;
use Memoize;
use Memoize;


Line 1,827: Line 1,827:
'fac2' => sub { fac2(50) },
'fac2' => sub { fac2(50) },
});
});
Benchmark::cmpthese($result);</lang>
Benchmark::cmpthese($result);</syntaxhighlight>
Output:
Output:
Benchmark: timing 100000 iterations of fac1, fac2...
Benchmark: timing 100000 iterations of fac1, fac2...
Line 1,837: Line 1,837:


Example without using Benchmark:
Example without using Benchmark:
<lang perl>sub cpu_time {
<syntaxhighlight lang="perl">sub cpu_time {
my ($user,$system,$cuser,$csystem) = times;
my ($user,$system,$cuser,$csystem) = times;
$user + $system
$user + $system
Line 1,862: Line 1,862:


printf "Sum(4) takes %f seconds.\n", time_it(\&sum, 4);
printf "Sum(4) takes %f seconds.\n", time_it(\&sum, 4);
# outputs "Sum(4) takes 0.280000 seconds."</lang>
# outputs "Sum(4) takes 0.280000 seconds."</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
Measures wall-clock time. On Windows the resolution is about 15ms. The elapsed function makes it more human-readable, eg elapsed(720) yields "12 minutes".
Measures wall-clock time. On Windows the resolution is about 15ms. The elapsed function makes it more human-readable, eg elapsed(720) yields "12 minutes".
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
Line 1,889: Line 1,889:
<span style="color: #000000;">time_it</span><span style="color: #0000FF;">(</span><span style="color: #000000;">identity</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">time_it</span><span style="color: #0000FF;">(</span><span style="color: #000000;">identity</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">time_it</span><span style="color: #0000FF;">(</span><span style="color: #000000;">total</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">time_it</span><span style="color: #0000FF;">(</span><span style="color: #000000;">total</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,897: Line 1,897:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>def count
<syntaxhighlight lang="phixmonti">def count
for drop endfor
for drop endfor
enddef
enddef
Line 1,905: Line 1,905:


10000000 count
10000000 count
msec t0 - print " seconds" print</lang>
msec t0 - print " seconds" print</syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
Line 1,912: Line 1,912:
* <code>statistics(runtime,[ProgTime,LastTime])</code>: <code>ProgTime</code> is the ms since program started, <code>LastTime</code> is the ms since last call to <code>statistics(runtime,_)</code>. It can be used to create user defined time predicates/functions, as show in <code>time1b/1</code>.
* <code>statistics(runtime,[ProgTime,LastTime])</code>: <code>ProgTime</code> is the ms since program started, <code>LastTime</code> is the ms since last call to <code>statistics(runtime,_)</code>. It can be used to create user defined time predicates/functions, as show in <code>time1b/1</code>.


<lang Picat>import cp.
<syntaxhighlight lang="picat">import cp.


go =>
go =>
Line 1,940: Line 1,940:
statistics(runtime, _),
statistics(runtime, _),
call(Goal),
call(Goal),
statistics(runtime, [_,T]).</lang>
statistics(runtime, [_,T]).</syntaxhighlight>


{{out}}
{{out}}
Line 1,955: Line 1,955:
There is another function, '[http://software-lab.de/doc/refT.html#tick tick]', which
There is another function, '[http://software-lab.de/doc/refT.html#tick tick]', which
also measures user time, and is used by the profiling tools.
also measures user time, and is used by the profiling tools.
<lang PicoLisp>: (bench (do 1000000 (* 3 4)))
<syntaxhighlight lang="picolisp">: (bench (do 1000000 (* 3 4)))
0.080 sec
0.080 sec
-> 12</lang>
-> 12</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
Line 1,964: Line 1,964:
function gauge(), but it could also be done manually with
function gauge(), but it could also be done manually with
gethrvtime() in ms or ns resolution.
gethrvtime() in ms or ns resolution.
<syntaxhighlight lang="pike">
<lang Pike>
void get_some_primes()
void get_some_primes()
{
{
Line 1,977: Line 1,977:
write("Wasted %f CPU seconds calculating primes\n", time_wasted);
write("Wasted %f CPU seconds calculating primes\n", time_wasted);
}
}
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,984: Line 1,984:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>declare (start_time, finish_time) float (18);
<syntaxhighlight lang="pl/i">declare (start_time, finish_time) float (18);


start_time = secs();
start_time = secs();
Line 1,998: Line 1,998:


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


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function fun($n){
function fun($n){
$res = 0
$res = 0
Line 2,014: Line 2,014:
}
}
"$((Measure-Command {fun 10000}).TotalSeconds) Seconds"
"$((Measure-Command {fun 10000}).TotalSeconds) Seconds"
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 2,023: Line 2,023:
===Built in timer===
===Built in timer===
This version uses the built in timer, on Windows it has an accuracy of ~10-15 msec.
This version uses the built in timer, on Windows it has an accuracy of ~10-15 msec.
<lang Purebasic>Procedure Foo(Limit)
<syntaxhighlight lang="purebasic">Procedure Foo(Limit)
Protected i, palindromic, String$
Protected i, palindromic, String$
For i=0 To Limit
For i=0 To Limit
Line 2,044: Line 2,044:
PrintN("and "+Str(cnt)+" are palindromic.")
PrintN("and "+Str(cnt)+" are palindromic.")
Print("Press ENTER to exit."): Input()
Print("Press ENTER to exit."): Input()
EndIf</lang>
EndIf</syntaxhighlight>


Starting timing of a calculation,
Starting timing of a calculation,
Line 2,056: Line 2,056:


This version uses a hi-res timer, but it is Windows only.
This version uses a hi-res timer, but it is Windows only.
<lang PureBasic>If OpenConsole()
<syntaxhighlight lang="purebasic">If OpenConsole()
Define Timed.f, cnt
Define Timed.f, cnt
PrintN("Starting timing of a calculation,")
PrintN("Starting timing of a calculation,")
Line 2,069: Line 2,069:
PrintN("and "+Str(cnt)+" are palindromic.")
PrintN("and "+Str(cnt)+" are palindromic.")
Print("Press ENTER to exit."): Input()
Print("Press ENTER to exit."): Input()
EndIf</lang>
EndIf</syntaxhighlight>


Starting timing of a calculation,
Starting timing of a calculation,
Line 2,078: Line 2,078:


This version still relies on the Windows API but does not make use of any additional libraries.
This version still relies on the Windows API but does not make use of any additional libraries.
<lang PureBasic>Procedure.f ticksHQ(reportIfPresent = #False)
<syntaxhighlight lang="purebasic">Procedure.f ticksHQ(reportIfPresent = #False)
Static maxfreq.q
Static maxfreq.q
Protected T.q
Protected T.q
Line 2,107: Line 2,107:
PrintN("and " + Str(cnt) + " are palindromic.")
PrintN("and " + Str(cnt) + " are palindromic.")
Print("Press ENTER to exit."): Input()
Print("Press ENTER to exit."): Input()
EndIf</lang>
EndIf</syntaxhighlight>


Sample output:
Sample output:
Line 2,119: Line 2,119:


'''Note:''' There is an overhead in executing a function that does nothing.
'''Note:''' There is an overhead in executing a function that does nothing.
<lang python>import sys, timeit
<syntaxhighlight lang="python">import sys, timeit
def usec(function, arguments):
def usec(function, arguments):
modname, funcname = __name__, function.__name__
modname, funcname = __name__, function.__name__
Line 2,137: Line 2,137:
from math import pow
from math import pow
def nothing(): pass
def nothing(): pass
def identity(x): return x</lang>
def identity(x): return x</syntaxhighlight>


===Example===
===Example===
Line 2,152: Line 2,152:
=={{header|R}}==
=={{header|R}}==
R has a built-in function, system.time, to calculate this.
R has a built-in function, system.time, to calculate this.
<lang R># A task
<syntaxhighlight lang="r"># A task
foo <- function()
foo <- function()
{
{
Line 2,164: Line 2,164:
timer <- system.time(foo())
timer <- system.time(foo())
# Extract the processing time
# Extract the processing time
timer["user.self"]</lang>
timer["user.self"]</syntaxhighlight>
For a breakdown of processing time by function, there is Rprof.
For a breakdown of processing time by function, there is Rprof.
<lang R>Rprof()
<syntaxhighlight lang="r">Rprof()
foo()
foo()
Rprof(NULL)
Rprof(NULL)
summaryRprof()</lang>
summaryRprof()</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(define (fact n) (if (zero? n) 1 (* n (fact (sub1 n)))))
(define (fact n) (if (zero? n) 1 (* n (fact (sub1 n)))))
(time (fact 5000))
(time (fact 5000))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
Follows modern trend toward measuring wall-clock time, since CPU time is becoming rather ill-defined in the age of multicore, and doesn't reflect IO overhead in any case.
Follows modern trend toward measuring wall-clock time, since CPU time is becoming rather ill-defined in the age of multicore, and doesn't reflect IO overhead in any case.
<lang perl6>my $start = now;
<syntaxhighlight lang="raku" line>my $start = now;
(^100000).pick(1000);
(^100000).pick(1000);
say now - $start;</lang>
say now - $start;</syntaxhighlight>
{{out}}
{{out}}
<pre>0.02301709</pre>
<pre>0.02301709</pre>


=={{header|Raven}}==
=={{header|Raven}}==
<lang Raven>define doId use $x
<syntaxhighlight lang="raven">define doId use $x
$x dup * $x /
$x dup * $x /


Line 2,209: Line 2,209:
42 "doId" timeFunc
42 "doId" timeFunc
12 2 "doPower" timeFunc
12 2 "doPower" timeFunc
"doSort" timeFunc</lang>
"doSort" timeFunc</syntaxhighlight>
{{out}}
{{out}}
<pre>2.193e-05 secs for NULL
<pre>2.193e-05 secs for NULL
Line 2,219: Line 2,219:
Retro has a '''time''' function returning the current time in seconds. This can be used to build a simple timing function:
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 ;
<syntaxhighlight lang="retro">: .runtime ( a- ) time [ do time ] dip - "\n%d\n" puts ;


: test 20000 [ putn space ] iterd ;
: test 20000 [ putn space ] iterd ;
&test .runtime</lang>
&test .runtime</syntaxhighlight>


Finer measurements are not possible with the standard implementation.
Finer measurements are not possible with the standard implementation.
Line 2,235: Line 2,235:
<br>there's a way to easily query the host (VM/CP) to indicate how much &nbsp; ''true'' &nbsp; CPU time was used by
<br>there's a way to easily query the host (VM/CP) to indicate how much &nbsp; ''true'' &nbsp; CPU time was used by
<br>(normally) your own userID.&nbsp; The result can then be placed into a REXX variable (as an option).
<br>(normally) your own userID.&nbsp; The result can then be placed into a REXX variable (as an option).
<lang rexx>/*REXX program displays the elapsed time for a REXX function (or subroutine). */
<syntaxhighlight lang="rexx">/*REXX program displays the elapsed time for a REXX function (or subroutine). */
arg reps . /*obtain an optional argument from C.L.*/
arg reps . /*obtain an optional argument from C.L.*/
if reps=='' then reps=100000 /*Not specified? No, then use default.*/
if reps=='' then reps=100000 /*Not specified? No, then use default.*/
Line 2,261: Line 2,261:
@.j=random() date() time() digits() fuzz() form() xrange() queued()
@.j=random() date() time() digits() fuzz() form() xrange() queued()
end /*j*/
end /*j*/
return j-1</lang>
return j-1</syntaxhighlight>
'''output''' &nbsp; when using a personal computer built in the 20th century:
'''output''' &nbsp; when using a personal computer built in the 20th century:
<pre>
<pre>
Line 2,281: Line 2,281:
<br>being measured is essentially the same as the wall clock time (duration) of the function execution; &nbsp; the
<br>being measured is essentially the same as the wall clock time (duration) of the function execution; &nbsp; the
<br>overhead of the invocation is minimal compared to the overall time used.
<br>overhead of the invocation is minimal compared to the overall time used.
<lang rexx>/*REXX program displays the elapsed time for a REXX function (or subroutine). */
<syntaxhighlight lang="rexx">/*REXX program displays the elapsed time for a REXX function (or subroutine). */
arg reps . /*obtain an optional argument from C.L.*/
arg reps . /*obtain an optional argument from C.L.*/
if reps=='' then reps=100000 /*Not specified? No, then use default.*/
if reps=='' then reps=100000 /*Not specified? No, then use default.*/
Line 2,307: Line 2,307:
@.j=random() date() time() digits() fuzz() form() xrange() queued()
@.j=random() date() time() digits() fuzz() form() xrange() queued()
end /*j*/
end /*j*/
return j-1</lang>
return j-1</syntaxhighlight>
'''output''' &nbsp; is essentially identical to the previous examples.
'''output''' &nbsp; is essentially identical to the previous examples.
<br><br>
<br><br>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
beginTime = TimeList()[13]
beginTime = TimeList()[13]
for n = 1 to 10000000
for n = 1 to 10000000
Line 2,320: Line 2,320:
elapsedTime = endTime - beginTime
elapsedTime = endTime - beginTime
see "Elapsed time = " + elapsedTime + nl
see "Elapsed time = " + elapsedTime + nl
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
Ruby's Benchmark module provides a way to generate nice reports (numbers are in seconds):
Ruby's Benchmark module provides a way to generate nice reports (numbers are in seconds):
<lang ruby>require 'benchmark'
<syntaxhighlight lang="ruby">require 'benchmark'


Benchmark.bm(8) do |x|
Benchmark.bm(8) do |x|
x.report("nothing:") { }
x.report("nothing:") { }
x.report("sum:") { (1..1_000_000).inject(4) {|sum, x| sum + x} }
x.report("sum:") { (1..1_000_000).inject(4) {|sum, x| sum + x} }
end</lang>
end</syntaxhighlight>
Output:
Output:
user system total real
user system total real
Line 2,336: Line 2,336:


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


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>// 20210224 Rust programming solution
<syntaxhighlight lang="rust">// 20210224 Rust programming solution


use rand::Rng;
use rand::Rng;
Line 2,363: Line 2,363:
println!("Time elapsed in the custom_function() is : {:?}", duration);
println!("Time elapsed in the custom_function() is : {:?}", duration);
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,371: Line 2,371:
=={{header|Scala}}==
=={{header|Scala}}==
Define a <code>time</code> function that returns the elapsed time (in ms) to execute a block of code.
Define a <code>time</code> function that returns the elapsed time (in ms) to execute a block of code.
<lang scala>
<syntaxhighlight lang="scala">
def time(f: => Unit)={
def time(f: => Unit)={
val s = System.currentTimeMillis
val s = System.currentTimeMillis
Line 2,377: Line 2,377:
System.currentTimeMillis - s
System.currentTimeMillis - s
}
}
</syntaxhighlight>
</lang>
Can be called with a code block:
Can be called with a code block:
<lang scala>
<syntaxhighlight lang="scala">
println(time {
println(time {
for(i <- 1 to 10000000) {}
for(i <- 1 to 10000000) {}
})
})
</syntaxhighlight>
</lang>
Or with a function:
Or with a function:
<lang scala>
<syntaxhighlight lang="scala">
def count(i:Int) = for(j <- 1 to i){}
def count(i:Int) = for(j <- 1 to i){}
println(time (count(10000000)))
println(time (count(10000000)))
</syntaxhighlight>
</lang>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(time (some-function))</lang>
<syntaxhighlight lang="scheme">(time (some-function))</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "time.s7i";
include "time.s7i";
include "duration.s7i";
include "duration.s7i";
Line 2,429: Line 2,429:
writeln("Identity(4) takes " <& timeIt(identity(4)));
writeln("Identity(4) takes " <& timeIt(identity(4)));
writeln("Sum(4) takes " <& timeIt(sum(4)));
writeln("Sum(4) takes " <& timeIt(sum(4)));
end func;</lang>
end func;</syntaxhighlight>


{{out}} of interpreted program:
{{out}} of interpreted program:
Line 2,440: Line 2,440:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var benchmark = frequire('Benchmark')
<syntaxhighlight lang="ruby">var benchmark = frequire('Benchmark')


func fac_rec(n) {
func fac_rec(n) {
Line 2,459: Line 2,459:
))
))


benchmark.cmpthese(result)</lang>
benchmark.cmpthese(result)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,471: Line 2,471:


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>
<syntaxhighlight lang="slate">
[inform: 2000 factorial] timeToRun.
[inform: 2000 factorial] timeToRun.
</syntaxhighlight>
</lang>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
(Squeak/Pharo/VisualWorks/SmalltalkX)
(Squeak/Pharo/VisualWorks/SmalltalkX)
<lang smalltalk>Time millisecondsToRun: [
<syntaxhighlight lang="smalltalk">Time millisecondsToRun: [
Transcript show: 2000 factorial
Transcript show: 2000 factorial
].</lang>
].</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>fun time_it (action, arg) = let
<syntaxhighlight lang="sml">fun time_it (action, arg) = let
val timer = Timer.startCPUTimer ()
val timer = Timer.startCPUTimer ()
val _ = action arg
val _ = action arg
Line 2,488: Line 2,488:
in
in
Time.+ (#usr times, #sys times)
Time.+ (#usr times, #sys times)
end</lang>
end</syntaxhighlight>


===Example===
===Example===
Line 2,508: Line 2,508:
Stata can track up to 100 timers. See '''[http://www.stata.com/help.cgi?timer timer]''' in Stata help.
Stata can track up to 100 timers. See '''[http://www.stata.com/help.cgi?timer timer]''' in Stata help.


<lang stata>program timer_test
<syntaxhighlight lang="stata">program timer_test
timer clear 1
timer clear 1
timer on 1
timer on 1
Line 2,517: Line 2,517:


. timer_test 1000
. timer_test 1000
1: 1.01 / 1 = 1.0140</lang>
1: 1.01 / 1 = 1.0140</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
Line 2,523: Line 2,523:
Using the 2-term ackermann function for demonstration.
Using the 2-term ackermann function for demonstration.


<lang swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


public struct TimeResult {
public struct TimeResult {
Line 2,578: Line 2,578:
let (n2, t2) = ClockTimer.time { ackermann(m: 4, n: 1) }
let (n2, t2) = ClockTimer.time { ackermann(m: 4, n: 1) }


print("Took \(t2.duration)s to calculate ackermann(m: 4, n: 1) = \(n2)")</lang>
print("Took \(t2.duration)s to calculate ackermann(m: 4, n: 1) = \(n2)")</syntaxhighlight>


{{out}}
{{out}}
Line 2,588: Line 2,588:
The Tcl <code>time</code> command returns the real time elapsed
The Tcl <code>time</code> command returns the real time elapsed
averaged over a number of iterations.
averaged over a number of iterations.
<lang tcl>proc sum_n {n} {
<syntaxhighlight lang="tcl">proc sum_n {n} {
for {set i 1; set sum 0.0} {$i <= $n} {incr i} {set sum [expr {$sum + $i}]}
for {set i 1; set sum 0.0} {$i <= $n} {incr i} {set sum [expr {$sum + $i}]}
return [expr {wide($sum)}]
return [expr {wide($sum)}]
Line 2,594: Line 2,594:


puts [time {sum_n 1e6} 100]
puts [time {sum_n 1e6} 100]
puts [time {} 100]</lang>
puts [time {} 100]</syntaxhighlight>
{{out}}
{{out}}
163551.0 microseconds per iteration
163551.0 microseconds per iteration
Line 2,604: Line 2,604:


Returns average time elapsed from many iterations.
Returns average time elapsed from many iterations.
<syntaxhighlight lang="torquescript">
<lang TorqueScript>
function benchmark(%times,%function,%a,%b,%c,%d,%e,%f,%g,%h,%i,%j,%k,%l,%m,%n,%o)
function benchmark(%times,%function,%a,%b,%c,%d,%e,%f,%g,%h,%i,%j,%k,%l,%m,%n,%o)
{
{
Line 2,628: Line 2,628:
return %result;
return %result;
}
}
</syntaxhighlight>
</lang>


{{out|Example}}
{{out|Example}}
<syntaxhighlight lang="torquescript">
<lang TorqueScript>
function exampleFunction(%var1,%var2)
function exampleFunction(%var1,%var2)
{
{
Line 2,641: Line 2,641:
==> BENCHMARKING RESULT FOR exampleFunction:
==> BENCHMARKING RESULT FOR exampleFunction:
==> 13.257
==> 13.257
</syntaxhighlight>
</lang>


=={{header|True BASIC}}==
=={{header|True BASIC}}==
{{trans|QBasic}}
{{trans|QBasic}}
<lang qbasic>SUB cont (n)
<syntaxhighlight lang="qbasic">SUB cont (n)
LET sum = 0
LET sum = 0
FOR i = 1 TO n
FOR i = 1 TO n
Line 2,660: Line 2,660:
LET timeelapsed = (timedone-timestart)*1000
LET timeelapsed = (timedone-timestart)*1000
PRINT timeelapsed; "miliseconds."
PRINT timeelapsed; "miliseconds."
END</lang>
END</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
SECTION test
SECTION test
Line 2,678: Line 2,678:
PRINT "'test' ends at ",time_end
PRINT "'test' ends at ",time_end
PRINT "'test' takes ",interval," seconds"
PRINT "'test' takes ",interval," seconds"
</syntaxhighlight>
</lang>
{{out}}
{{out}}
'test' start at 2011-01-15 14:38:22
'test' start at 2011-01-15 14:38:22
Line 2,685: Line 2,685:


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
<lang bash>$ time sleep 1</lang>
<syntaxhighlight lang="bash">$ time sleep 1</syntaxhighlight>


real 0m1.074s
real 0m1.074s
Line 2,692: Line 2,692:


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
<syntaxhighlight lang="vb">Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Private Function identity(x As Long) As Long
Private Function identity(x As Long) As Long
For j = 0 To 1000
For j = 0 To 1000
Line 2,718: Line 2,718:
finis_time = GetTickCount
finis_time = GetTickCount
Debug.Print "1000 times Sum(1) takes "; (finis_time - start_time); " milliseconds"
Debug.Print "1000 times Sum(1) takes "; (finis_time - start_time); " milliseconds"
End Sub</lang>{{out}}<pre>1000 times Identity(1) takes 0 seconds
End Sub</syntaxhighlight>{{out}}<pre>1000 times Identity(1) takes 0 seconds
1000 times Sum(1) takes 296 seconds</pre>
1000 times Sum(1) takes 296 seconds</pre>


=={{header|Wart}}==
=={{header|Wart}}==
<lang python>time 1+1
<syntaxhighlight lang="python">time 1+1
30000/1000000 # in microseconds
30000/1000000 # in microseconds
=> 2</lang>
=> 2</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-check}}
{{libheader|Wren-check}}
The only way Wren currently has to time a function (encapsulated in the ''Benchmark.run'' method) is to measure the System time before and after the function is called. We therefore use that approach, averaging over say 100 runs, having first shut down as many other processes as we can.
The only way Wren currently has to time a function (encapsulated in the ''Benchmark.run'' method) is to measure the System time before and after the function is called. We therefore use that approach, averaging over say 100 runs, having first shut down as many other processes as we can.
<lang ecmascript>import "./check" for Benchmark
<syntaxhighlight lang="ecmascript">import "./check" for Benchmark


Benchmark.run("a function", 100, true) {
Benchmark.run("a function", 100, true) {
for (i in 0..1e7) {}
for (i in 0..1e7) {}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,761: Line 2,761:
and thus the two values can be out of sync.
and thus the two values can be out of sync.


<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;
int T0, T1, I;
int T0, T1, I;
[T0:= GetTime;
[T0:= GetTime;
Line 2,767: Line 2,767:
T1:= GetTime;
T1:= GetTime;
IntOut(0, T1-T0); Text(0, " microseconds^M^J");
IntOut(0, T1-T0); Text(0, " microseconds^M^J");
]</lang>
]</syntaxhighlight>


{{out|Example output}} for a Duron 850 running DOS 5.0:
{{out|Example output}} for a Duron 850 running DOS 5.0:
Line 2,775: Line 2,775:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>sub count(n)
<syntaxhighlight lang="yabasic">sub count(n)
local i
local i
Line 2,788: Line 2,788:
t0 = peek("millisrunning")
t0 = peek("millisrunning")
count(10000000)
count(10000000)
print peek("millisrunning")-t0, " milliseconds"</lang>
print peek("millisrunning")-t0, " milliseconds"</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
In order to be as OS independent as possible, only system time is available.
In order to be as OS independent as possible, only system time is available.
<lang zkl>t:=Time.Clock.time; Atomic.sleep(3); (Time.Clock.time - t).println();</lang>
<syntaxhighlight lang="zkl">t:=Time.Clock.time; Atomic.sleep(3); (Time.Clock.time - t).println();</syntaxhighlight>
{{out}}
{{out}}
<pre>3</pre>
<pre>3</pre>