Time a function: Difference between revisions

m
syntax highlighting fixup automation
(add BQN)
m (syntax highlighting fixup automation)
Line 20:
{{trans|Nim}}
 
<langsyntaxhighlight lang="11l">F do_work(x)
V n = x
L(i) 10000000
Line 31:
R time:perf_counter() - start
 
print(time_func(() -> do_work(100)))</langsyntaxhighlight>
 
=={{header|8051 Assembly}}==
Line 47:
is (256^x - 1) * 2^(-p).
 
<langsyntaxhighlight lang="asm">TC EQU 8 ; number of counter registers
TSTART EQU 08h ; first register of timer counter
TEND EQU TSTART + TC - 1 ; end register of timer counter
Line 152:
 
END
</syntaxhighlight>
</lang>
 
=={{header|ACL2}}==
 
<langsyntaxhighlight Lisplang="lisp">(time$ (nthcdr 9999999 (take 10000000 nil)))</langsyntaxhighlight>
 
Output (for Clozure):
Line 165:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">BYTE RTCLOK1=$13
BYTE RTCLOK2=$14
BYTE PALNTSC=$D014
Line 208:
PrintF("%U ms%E",diffMs)
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Time_a_function.png Screenshot from Atari 8-bit computer]
Line 221:
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Calendar; use Ada.Calendar;
with Ada.Text_Io; use Ada.Text_Io;
 
Line 251:
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;</langsyntaxhighlight>
===Example===
Identity(4) takes 0.000001117 seconds.
Line 257:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">integer
identity(integer x)
{
Line 306:
 
0;
}</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program fcttime.s */
Line 540:
pop {r2-r4}
bx lr @ return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 572:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">benchmark [
print "starting function"
pause 2000
print "function ended"
]</langsyntaxhighlight>
 
{{out}}
Line 587:
===System time===
Uses system time, not process time
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % time("fx")
Return
 
Line 601:
%function%(parameter)
Return ElapsedTime := A_TickCount - StartTime . " milliseconds"
}</langsyntaxhighlight>
=== Using QueryPerformanceCounter ===
QueryPerformanceCounter allows even more precision:
<langsyntaxhighlight AHKlang="ahk">MsgBox, % TimeFunction("fx")
 
TimeFunction(Function, Parameters*) {
Line 619:
fx() {
Sleep, 1000
}</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang="freebasic">' Time a function
SUB timed()
SLEEP 7000
Line 632:
timed()
et = TIMER
PRINT st, ", ", et</langsyntaxhighlight>
 
{{out}}
Line 640:
=={{header|BASIC}}==
{{works with|QBasic}}
<langsyntaxhighlight lang="qbasic">DIM timestart AS SINGLE, timedone AS SINGLE, timeelapsed AS SINGLE
 
timestart = TIMER
Line 648:
'midnight check:
IF timedone < timestart THEN timedone = timedone + 86400
timeelapsed = timedone - timestart</langsyntaxhighlight>
 
See also: [[#BBC BASIC|BBC BASIC]], [[#PureBasic|PureBasic]].
 
=={{header|BASIC256}}==
<langsyntaxhighlight BASIC256lang="basic256">call cont(10000000)
print msec; " milliseconds"
 
Line 666:
sum += 1
next i
end subroutine</langsyntaxhighlight>
 
=={{header|Batch File}}==
Granularity: hundredths of second.
<syntaxhighlight lang="batch file">
<lang Batch File>
@echo off
Setlocal EnableDelayedExpansion
Line 693:
)
goto:eof
</syntaxhighlight>
</lang>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic">start%=TIME:REM centi-second timer
REM perform processing
lapsed%=TIME-start%</langsyntaxhighlight>
 
=={{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:
<syntaxhighlight lang ="bqn">F •_timed v</langsyntaxhighlight>
<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:
 
Here are a few example runs:
<langsyntaxhighlight lang="bqn"> {0:1;𝕩×𝕊𝕩-1}•_timed 100
8.437800000000001e¯05
{0:1;𝕩×𝕊𝕩-1}•_timed 1000
0.000299545</langsyntaxhighlight>
 
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( time
= fun funarg t0 ret
. !arg:(?fun.?funarg)
Line 728:
)
& time$(fib.30)
)</langsyntaxhighlight>
Output:
<pre>1346269.5,141*10E0 s</pre>
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>.)
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <time.h>
 
Line 776:
printf("sum (4) takes %lf s\n", time_it(sum, 4));
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
Line 782:
Using Stopwatch.
 
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Threading;
Line 803:
Enumerable.Range(1, 10000).Where(x => x % 2 == 0).Sum(); // Sum even numers from 1 to 10000
}
}</langsyntaxhighlight>
 
Using DateTime.
 
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Threading;
Line 827:
Enumerable.Range(1, 10000).Where(x => x % 2 == 0).Sum(); // Sum even numers from 1 to 10000
}
}</langsyntaxhighlight>
 
Output:
Line 833:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <ctime>
#include <iostream>
using namespace std;
Line 855:
cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl;
return 0;
}</langsyntaxhighlight>
 
===Example===
Line 862:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">
(defn fib []
(map first
Line 870:
 
(time (take 100 (fib)))
</syntaxhighlight>
</lang>
 
Output:
Line 880:
Common Lisp provides a standard utility for performance measurement, [http://www.lispworks.com/documentation/HyperSpec/Body/m_time.htm time]:
 
<langsyntaxhighlight lang="lisp">CL-USER> (time (reduce #'+ (make-list 100000 :initial-element 1)))
Evaluation took:
0.151 seconds of real time
Line 887:
0 calls to %EVAL
0 page faults and
2,400,256 bytes consed.</langsyntaxhighlight>
 
(The example output here is from [[SBCL]].)
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:
 
<langsyntaxhighlight lang="lisp">(defun timings (function)
(let ((real-base (get-internal-real-time))
(run-base (get-internal-run-time)))
Line 904:
CL-USER> (timings (lambda () (reduce #'+ (make-list 100000 :initial-element 1))))
17/500
7/250</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.datetime;
 
int identity(int x) {
Line 930:
writefln("identity(4) takes %f6 seconds.", timeIt(&identity, 4));
writefln("sum(4) takes %f seconds.", timeIt(&sum, 4));
}</langsyntaxhighlight>
Output:<pre>identity(4) takes 0.0000016 seconds.
sum(4) takes 0.522065 seconds.</pre>
===Using Tango===
<syntaxhighlight lang="d">
<lang d>
import tango.io.Stdout;
import tango.time.Clock;
Line 962:
Stdout.format("Sum(4) takes {:f6} seconds",timeIt(&sum,4)).newline;
}
</syntaxhighlight>
</lang>
 
=={{header|E}}==
Line 968:
{{trans|Java}} — E has no ''standardized'' facility for CPU time measurement; this {{works with|E-on-Java}}.
 
<langsyntaxhighlight lang="e">def countTo(x) {
println("Counting...")
for _ in 1..x {}
Line 984:
def finish := threadMX.getCurrentThreadCpuTime()
println(`Counting to $count takes ${(finish-start)//1000000}ms`)
}</langsyntaxhighlight>
 
=={{header|Elena}}==
{{trans|C#}}
ELENA 4.x :
<langsyntaxhighlight lang="elena">import system'calendar;
import system'routines;
import system'threading;
Line 1,011:
console.printLine("Time elapsed in msec:",(end - start).Milliseconds)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,020:
{{trans|Erlang}}
'''tc/1'''
<langsyntaxhighlight lang="elixir">iex(10)> :timer.tc(fn -> Enum.each(1..100000, fn x -> x*x end) end)
{236000, :ok}</langsyntaxhighlight>
'''tc/2'''
<langsyntaxhighlight lang="elixir">iex(11)> :timer.tc(fn x -> Enum.each(1..x, fn y -> y*y end) end, [1000000])
{2300000, :ok}</langsyntaxhighlight>
'''tc/3'''
<langsyntaxhighlight lang="elixir">iex(12)> :timer.tc(Enum, :to_list, [1..1000000])
{224000,
[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,
42, 43, 44, 45, 46, 47, 48, 49, ...]}</langsyntaxhighlight>
 
=={{header|Erlang}}==
Line 1,036:
 
'''tc/1''' takes a 0-arity function and executes it:
<langsyntaxhighlight lang="erlang">
5> {Time,Result} = timer:tc(fun () -> lists:foreach(fun(X) -> X*X end, lists:seq(1,100000)) end).
{226391,ok}
Line 1,042:
0.226391
7> % Time is in microseconds.
</syntaxhighlight>
</lang>
'''tc/2''' takes an n-arity function and its arguments:
<langsyntaxhighlight lang="erlang">
9> timer:tc(fun (X) -> lists:foreach(fun(Y) -> Y*Y end, lists:seq(1,X)) end, [1000000]).
{2293844,ok}
</syntaxhighlight>
</lang>
'''tc/3''' takes a module name, function name and the list of arguments to the function:
<langsyntaxhighlight lang="erlang">
8> timer:tc(lists,seq,[1,1000000]).
{62370,
[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|...]}
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">atom t
t = time()
some_procedure()
t = time() - t
printf(1,"Elapsed %f seconds.\n",t)</langsyntaxhighlight>
 
=={{header|F Sharp|F#}}==
The .Net framework provides a Stopwatch class which provides a performance counter.
<langsyntaxhighlight lang="fsharp">
open System.Diagnostics
let myfunc data =
Line 1,074:
printf "elapsed %d ms" timer.ElapsedMilliseconds
result
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
{{works with|Factor|0.98}}
<langsyntaxhighlight lang="factor">USING: kernel sequences tools.time ;
 
[ 10000 <iota> sum drop ] time</langsyntaxhighlight>
{{out}}
<pre>
Line 1,094:
=={{header|Forth}}==
{{works with|GNU Forth}}
<langsyntaxhighlight lang="forth">: time: ( "word" -- )
utime 2>R ' EXECUTE
utime 2R> D-
<# # # # # # # [CHAR] . HOLD #S #> TYPE ." seconds" ;
 
1000 time: MS \ 1.000081 seconds ok</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Gfortran}} version 4.4.5 (Debian 4.4.5-8) on x86_64-linux-gnu
 
<langsyntaxhighlight lang="fortran">
c The subroutine to analyze
subroutine do_something()
Line 1,123:
return
end
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function sumToLimit(limit As UInteger) As UInteger
Line 1,144:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,153:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Return the time passed in last function
time;</langsyntaxhighlight>
 
=={{header|Go}}==
Line 1,160:
The Go command line tool <code>go test</code> includes [http://golang.org/pkg/testing/#hdr-Benchmarks benchmarking support].
Given a package with functions:
<langsyntaxhighlight lang="go">package empty
 
func Empty() {}
Line 1,168:
for i := 0; i < 1e6; i++ {
}
}</langsyntaxhighlight>
the following code, placed in a file whose name ends in <tt>_test.go</tt>, will time them:
<langsyntaxhighlight lang="go">package empty
 
import "testing"
Line 1,184:
Count()
}
}</langsyntaxhighlight>
<code>go test</code> varies <code>b.N</code> to get meaningful resolution.
Example:
Line 1,202:
===testing.Benchmark===
The benchmarking features of the <code>testing</code> package are exported for use within a Go program.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,232:
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))
}</langsyntaxhighlight>
{{out}}
<pre>
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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,270:
empty()
count()
}</langsyntaxhighlight>
Output:
<pre>
Line 1,280:
{{trans|Java}}
===CPU Timing===
<langsyntaxhighlight lang="groovy">import java.lang.management.ManagementFactory
import java.lang.management.ThreadMXBean
 
Line 1,291:
c.call()
(threadMX.currentThreadCpuTime - start)/1000000
}</langsyntaxhighlight>
 
===Wall Clock Timing===
<langsyntaxhighlight lang="groovy">def clockRealTime = { Closure c ->
def start = System.currentTimeMillis()
c.call()
System.currentTimeMillis() - start
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">def countTo = { Long n ->
long i = 0; while(i < n) { i += 1L }
}
Line 1,311:
println "Counting to ${testSize} takes ${measuredTime}ms of ${measurementType}"
}
}</langsyntaxhighlight>
 
Output:
Line 1,322:
 
=={{header|Halon}}==
<langsyntaxhighlight lang="halon">$t = uptime();
 
sleep(1);
 
echo uptime() - $t;</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import System.CPUTime (getCPUTime)
 
-- We assume the function we are timing is an IO monad computation
Line 1,341:
-- Version for use with evaluating regular non-monadic functions
timeIt_ :: (Fractional c) => (a -> b) -> a -> IO c
timeIt_ f = timeIt ((`seq` return ()) . f)</langsyntaxhighlight>
 
===Example===
Line 1,351:
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">t_start = TIME() ! returns seconds since midnight
SYSTEM(WAIT = 1234) ! wait 1234 milliseconds
t_end = TIME()
 
WRITE(StatusBar) t_end - t_start, " seconds"</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight Iconlang="icon">procedure timef(f) #: time a function f
local gcol,alloc,used,size,runtime,header,x,i
 
Line 1,394:
write("Note: static region values should be zero and may not be meaningful.")
return
end</langsyntaxhighlight>
 
Sample usage:<langsyntaxhighlight Iconlang="icon">procedure main()
timef(perfectnumbers)
end
 
procedure perfectnumbers()
...</langsyntaxhighlight>
 
Sample output (from the [[Perfect_numbers#Icon_and_Unicon|Perfect Numbers]] task):
Line 1,421:
 
=={{header|Ioke}}==
<langsyntaxhighlight lang="ioke">use("benchmark")
 
func = method((1..50000) reduce(+))
 
Benchmark report(1, 1, func)</langsyntaxhighlight>
 
=={{header|J}}==
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.
===Example===
<langsyntaxhighlight lang="j"> (6!:2 , 7!:2) '|: 50 50 50 $ i. 50^3'
0.00488008 3.14829e6
timespacex '|: 50 50 50 $ i. 50^3'
0.00388519 3.14829e6</langsyntaxhighlight>
=={{header|Janet}}==
<langsyntaxhighlight Clojurelang="clojure">(defmacro time
"Print the time it takes to evaluate body to stderr.\n
Evaluates to body."
Line 1,446:
,$val)))
 
(time (os/sleep 0.5))</langsyntaxhighlight>
{{out}}
<pre>0.500129</pre>
Line 1,452:
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java">import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
 
Line 1,478:
System.out.println("Done!");
}
}</langsyntaxhighlight>
 
Measures real time rather than CPU time:
{{works with|Java|(all versions)}}
 
<langsyntaxhighlight lang="java"> public static void main(String[] args){
long start, end;
start = System.currentTimeMillis();
Line 1,494:
System.out.println("Counting to 1000000000 takes "+(end-start)+"ms");
 
}</langsyntaxhighlight>
Output:
Counting...
Line 1,504:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">
function test() {
let n = 0
Line 1,517:
 
console.log('test() took ' + ((end - start) / 1000) + ' seconds') // test() took 0.001 seconds
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia"># v0.6.0
 
function countto(n::Integer)
Line 1,532:
 
@time countto(10 ^ 5)
@time countto(10 ^ 10)</langsyntaxhighlight>
 
{{out}}
Line 1,546:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.1.2
// need to enable runtime assertions with JVM -ea option
 
Line 1,569:
println("Counting to $count takes ${(end-start)/1000000}ms")
}
}</langsyntaxhighlight>
This is a typical result (sometimes the second figure is only about 1400ms - no idea why)
{{out}}
Line 1,582:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(start = micros)
loop(100000) => {
'nothing is outout because no autocollect'
}
'time for 100,000 loop repititions: '+(micros - #start)+' microseconds'</langsyntaxhighlight>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">on testFunc ()
repeat with i = 1 to 1000000
x = sqrt(log(i))
end repeat
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lingo">ms = _system.milliseconds
testFunc()
ms = _system.milliseconds - ms
put "Execution time in ms:" && ms
-- "Execution time in ms: 983"</langsyntaxhighlight>
 
=={{header|Logo}}==
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.
 
<langsyntaxhighlight lang="logo">to time
output first first shell "|date +%s|
end
Line 1,615:
end
 
elapsed [wait 300] ; 5 seconds elapsed</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function Test_Function()
for i = 1, 10000000 do
local s = math.log( i )
Line 1,629:
t2 = os.clock()
 
print( os.difftime( t2, t1 ) )</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 1,647:
10000 is Double (default)
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module sumtolimit (limit) {
Line 1,676:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight lang="maple">CodeTools:-Usage(ifactor(32!+1), output = realtime, quiet);</langsyntaxhighlight>
<langsyntaxhighlight lang="maple">CodeTools:-Usage(ifactor(32!+1), output = cputime, quiet);</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang Mathematica="mathematica">AbsoluteTiming[x];</langsyntaxhighlight>
where x is an operation. Example calculating a million digits of Sqrt[3]:
<langsyntaxhighlight Mathematicalang="mathematica">AbsoluteTiming[N[Sqrt[3], 10^6]]</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight Mathematicalang="mathematica">{0.000657, 1.7320508075688772935274463......}</langsyntaxhighlight>
First elements if the time in seconds, second elements if the result from the operation. Note that I truncated the result.
 
=={{header|Maxima}}==
<langsyntaxhighlight 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.
Line 1,707:
f(24);
Evaluation took 0.9400 seconds (0.9400 elapsed)
46368</langsyntaxhighlight>
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">start = time
for i in range(1,100000)
end for
duration = time - start
print "Process took " + duration + " seconds"</langsyntaxhighlight>
{{out}}
<pre>
Line 1,721:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import times, strutils
proc doWork(x: int) =
Line 1,733:
cpuTime() - t0
echo "Time = ", time(doWork(100)).formatFloat(ffDecimal, precision = 3), " s"</langsyntaxhighlight>
 
{{out}}
Line 1,740:
 
=={{header|OCaml}}==
<langsyntaxhighlight 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</langsyntaxhighlight>
 
===Example===
Line 1,772:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
%% returns milliseconds
fun {TimeIt Proc}
Line 1,790:
{FoldL {List.number 1 1000000 1} Number.'+' 4 _}
end}
}</langsyntaxhighlight>
 
=={{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=
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.
<langsyntaxhighlight lang="parigp">time(foo)={
foo();
gettime();
}</langsyntaxhighlight>
 
Alternate version:
{{works with|PARI/GP|2.6.2+}}
<langsyntaxhighlight lang="parigp">time(foo)={
my(start=getabstime());
foo();
getabstime()-start;
}</langsyntaxhighlight>
 
=={{header|Perl}}==
Example of using the built-in Benchmark core module - it compares two versions of recursive factorial functions:
<langsyntaxhighlight lang="perl">use Benchmark;
use Memoize;
 
Line 1,827:
'fac2' => sub { fac2(50) },
});
Benchmark::cmpthese($result);</langsyntaxhighlight>
Output:
Benchmark: timing 100000 iterations of fac1, fac2...
Line 1,837:
 
Example without using Benchmark:
<langsyntaxhighlight lang="perl">sub cpu_time {
my ($user,$system,$cuser,$csystem) = times;
$user + $system
Line 1,862:
 
printf "Sum(4) takes %f seconds.\n", time_it(\&sum, 4);
# outputs "Sum(4) takes 0.280000 seconds."</langsyntaxhighlight>
 
=={{header|Phix}}==
{{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".
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
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;">total</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,897:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">def count
for drop endfor
enddef
Line 1,905:
 
10000000 count
msec t0 - print " seconds" print</langsyntaxhighlight>
 
=={{header|Picat}}==
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>.
 
<langsyntaxhighlight Picatlang="picat">import cp.
 
go =>
Line 1,940:
statistics(runtime, _),
call(Goal),
statistics(runtime, [_,T]).</langsyntaxhighlight>
 
{{out}}
Line 1,955:
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.
<langsyntaxhighlight PicoLisplang="picolisp">: (bench (do 1000000 (* 3 4)))
0.080 sec
-> 12</langsyntaxhighlight>
 
=={{header|Pike}}==
Line 1,964:
function gauge(), but it could also be done manually with
gethrvtime() in ms or ns resolution.
<syntaxhighlight lang="pike">
<lang Pike>
void get_some_primes()
{
Line 1,977:
write("Wasted %f CPU seconds calculating primes\n", time_wasted);
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,984:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">declare (start_time, finish_time) float (18);
 
start_time = secs();
Line 1,998:
 
/* Note: using the SECS function takes into account the clock */
/* going past midnight. */</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function fun($n){
$res = 0
Line 2,014:
}
"$((Measure-Command {fun 10000}).TotalSeconds) Seconds"
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,023:
===Built in timer===
This version uses the built in timer, on Windows it has an accuracy of ~10-15 msec.
<langsyntaxhighlight Purebasiclang="purebasic">Procedure Foo(Limit)
Protected i, palindromic, String$
For i=0 To Limit
Line 2,044:
PrintN("and "+Str(cnt)+" are palindromic.")
Print("Press ENTER to exit."): Input()
EndIf</langsyntaxhighlight>
 
Starting timing of a calculation,
Line 2,056:
 
This version uses a hi-res timer, but it is Windows only.
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
Define Timed.f, cnt
PrintN("Starting timing of a calculation,")
Line 2,069:
PrintN("and "+Str(cnt)+" are palindromic.")
Print("Press ENTER to exit."): Input()
EndIf</langsyntaxhighlight>
 
Starting timing of a calculation,
Line 2,078:
 
This version still relies on the Windows API but does not make use of any additional libraries.
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.f ticksHQ(reportIfPresent = #False)
Static maxfreq.q
Protected T.q
Line 2,107:
PrintN("and " + Str(cnt) + " are palindromic.")
Print("Press ENTER to exit."): Input()
EndIf</langsyntaxhighlight>
 
Sample output:
Line 2,119:
 
'''Note:''' There is an overhead in executing a function that does nothing.
<langsyntaxhighlight lang="python">import sys, timeit
def usec(function, arguments):
modname, funcname = __name__, function.__name__
Line 2,137:
from math import pow
def nothing(): pass
def identity(x): return x</langsyntaxhighlight>
 
===Example===
Line 2,152:
=={{header|R}}==
R has a built-in function, system.time, to calculate this.
<langsyntaxhighlight Rlang="r"># A task
foo <- function()
{
Line 2,164:
timer <- system.time(foo())
# Extract the processing time
timer["user.self"]</langsyntaxhighlight>
For a breakdown of processing time by function, there is Rprof.
<langsyntaxhighlight Rlang="r">Rprof()
foo()
Rprof(NULL)
summaryRprof()</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
(define (fact n) (if (zero? n) 1 (* n (fact (sub1 n)))))
(time (fact 5000))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(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.
<syntaxhighlight lang="raku" perl6line>my $start = now;
(^100000).pick(1000);
say now - $start;</langsyntaxhighlight>
{{out}}
<pre>0.02301709</pre>
 
=={{header|Raven}}==
<langsyntaxhighlight Ravenlang="raven">define doId use $x
$x dup * $x /
 
Line 2,209:
42 "doId" timeFunc
12 2 "doPower" timeFunc
"doSort" timeFunc</langsyntaxhighlight>
{{out}}
<pre>2.193e-05 secs for NULL
Line 2,219:
Retro has a '''time''' function returning the current time in seconds. This can be used to build a simple timing function:
 
<langsyntaxhighlight Retrolang="retro">: .runtime ( a- ) time [ do time ] dip - "\n%d\n" puts ;
 
: test 20000 [ putn space ] iterd ;
&test .runtime</langsyntaxhighlight>
 
Finer measurements are not possible with the standard implementation.
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>(normally) your own userID.&nbsp; The result can then be placed into a REXX variable (as an option).
<langsyntaxhighlight lang="rexx">/*REXX program displays the elapsed time for a REXX function (or subroutine). */
arg reps . /*obtain an optional argument from C.L.*/
if reps=='' then reps=100000 /*Not specified? No, then use default.*/
Line 2,261:
@.j=random() date() time() digits() fuzz() form() xrange() queued()
end /*j*/
return j-1</langsyntaxhighlight>
'''output''' &nbsp; when using a personal computer built in the 20th century:
<pre>
Line 2,281:
<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.
<langsyntaxhighlight lang="rexx">/*REXX program displays the elapsed time for a REXX function (or subroutine). */
arg reps . /*obtain an optional argument from C.L.*/
if reps=='' then reps=100000 /*Not specified? No, then use default.*/
Line 2,307:
@.j=random() date() time() digits() fuzz() form() xrange() queued()
end /*j*/
return j-1</langsyntaxhighlight>
'''output''' &nbsp; is essentially identical to the previous examples.
<br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
beginTime = TimeList()[13]
for n = 1 to 10000000
Line 2,320:
elapsedTime = endTime - beginTime
see "Elapsed time = " + elapsedTime + nl
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
Ruby's Benchmark module provides a way to generate nice reports (numbers are in seconds):
<langsyntaxhighlight 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</langsyntaxhighlight>
Output:
user system total real
Line 2,336:
 
You can get the total time as a number for later processing like this:
<langsyntaxhighlight lang="ruby">Benchmark.measure { whatever }.total</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">// 20210224 Rust programming solution
 
use rand::Rng;
Line 2,363:
println!("Time elapsed in the custom_function() is : {:?}", duration);
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,371:
=={{header|Scala}}==
Define a <code>time</code> function that returns the elapsed time (in ms) to execute a block of code.
<langsyntaxhighlight lang="scala">
def time(f: => Unit)={
val s = System.currentTimeMillis
Line 2,377:
System.currentTimeMillis - s
}
</syntaxhighlight>
</lang>
Can be called with a code block:
<langsyntaxhighlight lang="scala">
println(time {
for(i <- 1 to 10000000) {}
})
</syntaxhighlight>
</lang>
Or with a function:
<langsyntaxhighlight lang="scala">
def count(i:Int) = for(j <- 1 to i){}
println(time (count(10000000)))
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
<syntaxhighlight lang ="scheme">(time (some-function))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "time.s7i";
include "duration.s7i";
Line 2,429:
writeln("Identity(4) takes " <& timeIt(identity(4)));
writeln("Sum(4) takes " <& timeIt(sum(4)));
end func;</langsyntaxhighlight>
 
{{out}} of interpreted program:
Line 2,440:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var benchmark = frequire('Benchmark')
 
func fac_rec(n) {
Line 2,459:
))
 
benchmark.cmpthese(result)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,471:
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">
[inform: 2000 factorial] timeToRun.
</syntaxhighlight>
</lang>
 
=={{header|Smalltalk}}==
(Squeak/Pharo/VisualWorks/SmalltalkX)
<langsyntaxhighlight lang="smalltalk">Time millisecondsToRun: [
Transcript show: 2000 factorial
].</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">fun time_it (action, arg) = let
val timer = Timer.startCPUTimer ()
val _ = action arg
Line 2,488:
in
Time.+ (#usr times, #sys times)
end</langsyntaxhighlight>
 
===Example===
Line 2,508:
Stata can track up to 100 timers. See '''[http://www.stata.com/help.cgi?timer timer]''' in Stata help.
 
<langsyntaxhighlight lang="stata">program timer_test
timer clear 1
timer on 1
Line 2,517:
 
. timer_test 1000
1: 1.01 / 1 = 1.0140</langsyntaxhighlight>
 
=={{header|Swift}}==
Line 2,523:
Using the 2-term ackermann function for demonstration.
 
<langsyntaxhighlight lang="swift">import Foundation
 
public struct TimeResult {
Line 2,578:
let (n2, t2) = ClockTimer.time { ackermann(m: 4, n: 1) }
 
print("Took \(t2.duration)s to calculate ackermann(m: 4, n: 1) = \(n2)")</langsyntaxhighlight>
 
{{out}}
Line 2,588:
The Tcl <code>time</code> command returns the real time elapsed
averaged over a number of iterations.
<langsyntaxhighlight 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)}]
Line 2,594:
 
puts [time {sum_n 1e6} 100]
puts [time {} 100]</langsyntaxhighlight>
{{out}}
163551.0 microseconds per iteration
Line 2,604:
 
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)
{
Line 2,628:
return %result;
}
</syntaxhighlight>
</lang>
 
{{out|Example}}
<syntaxhighlight lang="torquescript">
<lang TorqueScript>
function exampleFunction(%var1,%var2)
{
Line 2,641:
==> BENCHMARKING RESULT FOR exampleFunction:
==> 13.257
</syntaxhighlight>
</lang>
 
=={{header|True BASIC}}==
{{trans|QBasic}}
<langsyntaxhighlight lang="qbasic">SUB cont (n)
LET sum = 0
FOR i = 1 TO n
Line 2,660:
LET timeelapsed = (timedone-timestart)*1000
PRINT timeelapsed; "miliseconds."
END</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
SECTION test
Line 2,678:
PRINT "'test' ends at ",time_end
PRINT "'test' takes ",interval," seconds"
</syntaxhighlight>
</lang>
{{out}}
'test' start at 2011-01-15 14:38:22
Line 2,685:
 
=={{header|UNIX Shell}}==
<syntaxhighlight lang ="bash">$ time sleep 1</langsyntaxhighlight>
 
real 0m1.074s
Line 2,692:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Private Function identity(x As Long) As Long
For j = 0 To 1000
Line 2,718:
finis_time = GetTickCount
Debug.Print "1000 times Sum(1) takes "; (finis_time - start_time); " milliseconds"
End Sub</langsyntaxhighlight>{{out}}<pre>1000 times Identity(1) takes 0 seconds
1000 times Sum(1) takes 296 seconds</pre>
 
=={{header|Wart}}==
<langsyntaxhighlight lang="python">time 1+1
30000/1000000 # in microseconds
=> 2</langsyntaxhighlight>
 
=={{header|Wren}}==
{{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.
<langsyntaxhighlight lang="ecmascript">import "./check" for Benchmark
 
Benchmark.run("a function", 100, true) {
for (i in 0..1e7) {}
}</langsyntaxhighlight>
 
{{out}}
Line 2,761:
and thus the two values can be out of sync.
 
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
int T0, T1, I;
[T0:= GetTime;
Line 2,767:
T1:= GetTime;
IntOut(0, T1-T0); Text(0, " microseconds^M^J");
]</langsyntaxhighlight>
 
{{out|Example output}} for a Duron 850 running DOS 5.0:
Line 2,775:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">sub count(n)
local i
Line 2,788:
t0 = peek("millisrunning")
count(10000000)
print peek("millisrunning")-t0, " milliseconds"</langsyntaxhighlight>
 
=={{header|zkl}}==
In order to be as OS independent as possible, only system time is available.
<langsyntaxhighlight lang="zkl">t:=Time.Clock.time; Atomic.sleep(3); (Time.Clock.time - t).println();</langsyntaxhighlight>
{{out}}
<pre>3</pre>
10,327

edits