Time a function: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(46 intermediate revisions by 30 users not shown)
Line 16:
This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].
<br><br>
 
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">F do_work(x)
V n = x
L(i) 10000000
n += i
R n
 
F time_func(f)
V start = time:perf_counter()
f()
R time:perf_counter() - start
 
print(time_func(() -> do_work(100)))</syntaxhighlight>
 
=={{header|8051 Assembly}}==
Line 31 ⟶ 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 136 ⟶ 152:
 
END
</syntaxhighlight>
</lang>
 
=={{header|ACL2}}==
 
<langsyntaxhighlight Lisplang="lisp">(time$ (nthcdr 9999999 (take 10000000 nil)))</langsyntaxhighlight>
 
Output (for Clozure):
Line 147 ⟶ 163:
; (160,001,648 bytes allocated).
(NIL)</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE RTCLOK1=$13
BYTE RTCLOK2=$14
BYTE PALNTSC=$D014
 
PROC Count(CARD max)
CARD i
 
FOR i=1 TO max DO OD
RETURN
 
CARD FUNC GetFrame()
CARD res
BYTE lsb=res,msb=res+1
 
lsb=RTCLOK2
msb=RTCLOK1
RETURN (res)
 
CARD FUNC FramesToMs(CARD frames)
CARD res
 
IF PALNTSC=15 THEN
res=frames*60
ELSE
res=frames*50
FI
RETURN (res)
 
PROC Main()
CARD ARRAY c=[1000 2000 5000 10000 20000 50000]
CARD beg,end,diff,diffMs
BYTE i
 
FOR i=0 TO 5
DO
PrintF("Count to %U takes ",c(i))
beg=GetFrame()
Count(c(i))
end=GetFrame()
diff=end-beg
diffMs=FramesToMs(diff)
PrintF("%U ms%E",diffMs)
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Time_a_function.png Screenshot from Atari 8-bit computer]
<pre>
Count to 1000 takes 50 ms
Count to 2000 takes 100 ms
Count to 5000 takes 300 ms
Count to 10000 takes 600 ms
Count to 20000 takes 1150 ms
Count to 50000 takes 3000 ms
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Calendar; use Ada.Calendar;
with Ada.Text_Io; use Ada.Text_Io;
 
Line 179 ⟶ 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 185 ⟶ 257:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">integer
identity(integer x)
{
Line 234 ⟶ 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 467 ⟶ 540:
pop {r2-r4}
bx lr @ return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 499 ⟶ 572:
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">benchmark [
<lang arturo>func: {
print "starting function"
delay 2000
pause 2000
}
print "function ended"
 
]</syntaxhighlight>
print "Function took: " + [benchmark func] + "s"</lang>
 
{{out}}
 
<pre>starting function
<pre>Function took: 2001ms</pre>
function ended
[benchmark] time: 2.005s</pre>
 
=={{header|AutoHotkey}}==
===System time===
Uses system time, not process time
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % time("fx")
Return
 
Line 526 ⟶ 601:
%function%(parameter)
Return ElapsedTime := A_TickCount - StartTime . " milliseconds"
}</langsyntaxhighlight>
=== Using QueryPerformanceCounter ===
QueryPerformanceCounter allows even more precision:
<langsyntaxhighlight AHKlang="ahk">MsgBox, % timeTimeFunction("fx")
 
TimeFunction(Function, Parameters*) {
time(function, parameter=0){
SetBatchLines, -1 ; SetBatchLines sets the speed of which every new line of coe is run.
SetBatchLines -1
DllCall("QueryPerformanceCounter", "Int64*", CounterBefore) ; Start the counter.
DllCall("QueryPerformanceFrequency", "Int64*", Freq) ; Get the frequency of the counter.
%Function%(Parameters*) ; Call the function with it's parameters.
%function%(parameter)
DllCall("QueryPerformanceCounter", "Int64*", CounterAfter) ; End the counter.
 
return (CounterAfter-CounterBefore)/Freq * 1000 " milliseconds"
; Calculate the speed of which it counted.
Return, (((CounterAfter - CounterBefore) / Freq) * 1000) . " milliseconds."
}
 
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 555 ⟶ 632:
timed()
et = TIMER
PRINT st, ", ", et</langsyntaxhighlight>
 
{{out}}
Line 563 ⟶ 640:
=={{header|BASIC}}==
{{works with|QBasic}}
<langsyntaxhighlight lang="qbasic">DIM timestart AS SINGLE, timedone AS SINGLE, timeelapsed AS SINGLE
 
timestart = TIMER
Line 571 ⟶ 648:
'midnight check:
IF timedone < timestart THEN timedone = timedone + 86400
timeelapsed = timedone - timestart</langsyntaxhighlight>
 
See also: [[#BBC BASIC|BBC BASIC]], [[#PureBasic|PureBasic]].
 
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">call cont(10000000)
print msec; " milliseconds"
 
t0 = msec
call cont(10000000)
print msec+t0; " milliseconds"
end
 
subroutine cont(n)
sum = 0
for i = 1 to n
sum += 1
next i
end subroutine</syntaxhighlight>
 
=={{header|Batch File}}==
Granularity: hundredths of second.
<syntaxhighlight lang="batch file">
<lang Batch File>
@echo off
Setlocal EnableDelayedExpansion
Line 600 ⟶ 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</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.
 
The final result is in seconds.
 
Here are a few example runs:
<syntaxhighlight lang="bqn"> {0:1;𝕩×𝕊𝕩-1}•_timed 100
8.437800000000001e¯05
{0:1;𝕩×𝕊𝕩-1}•_timed 1000
0.000299545</syntaxhighlight>
 
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( time
= fun funarg t0 ret
. !arg:(?fun.?funarg)
Line 621 ⟶ 728:
)
& time$(fib.30)
)</langsyntaxhighlight>
Output:
<pre>1346269.5,141*10E0 s</pre>
Line 631 ⟶ 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 669 ⟶ 776:
printf("sum (4) takes %lf s\n", time_it(sum, 4));
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
<lang cpp>#include <ctime>
#include <iostream>
using namespace std;
 
int identity(int x) { return x; }
int sum(int num) {
for (int i = 0; i < 1000000; i++)
num += i;
return num;
}
 
double time_it(int (*action)(int), int arg) {
clock_t start_time = clock();
action(arg);
clock_t finis_time = clock();
return ((double) (finis_time - start_time)) / CLOCKS_PER_SEC;
}
 
int main() {
cout << "Identity(4) takes " << time_it(identity, 4) << " seconds." << endl;
cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl;
return 0;
}</lang>
 
===Example===
Identity(4) takes 0 seconds.
Sum(4) takes 0.01 seconds.
 
=={{header|C sharp|C#}}==
Line 704 ⟶ 782:
Using Stopwatch.
 
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Threading;
Line 725 ⟶ 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 749 ⟶ 827:
Enumerable.Range(1, 10000).Where(x => x % 2 == 0).Sum(); // Sum even numers from 1 to 10000
}
}</langsyntaxhighlight>
 
Output:
DoSomething() took 1071,5408ms
 
=={{header|C++}}==
===Using <code>ctime</code>===
<syntaxhighlight lang="cpp">#include <ctime>
#include <iostream>
using namespace std;
 
int identity(int x) { return x; }
int sum(int num) {
for (int i = 0; i < 1000000; i++)
num += i;
return num;
}
 
double time_it(int (*action)(int), int arg) {
clock_t start_time = clock();
action(arg);
clock_t finis_time = clock();
return ((double) (finis_time - start_time)) / CLOCKS_PER_SEC;
}
 
int main() {
cout << "Identity(4) takes " << time_it(identity, 4) << " seconds." << endl;
cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl;
return 0;
}</syntaxhighlight>
 
Output:
<pre>
Identity(4) takes 0 seconds.
Sum(4) takes 0.01 seconds.
</pre>
 
===Using <code>std::chrono</code>===
 
<syntaxhighlight lang="cpp">
// Compile with:
// g++ -std=c++20 -Wall -Wextra -pedantic -O0 func-time.cpp -o func-time
 
#include <iostream>
#include <chrono>
 
template<typename f>
double measure(f func) {
auto start = std::chrono::steady_clock::now(); // Starting point
(*func)(); // Run the function
auto end = std::chrono::steady_clock::now(); // End point
return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); // By default, return time by milliseconds
}
 
/*
Test functions:
identity(): returns a number
addmillion(): add 1,000,000 to a number, one by one, using a for-loop
*/
 
int identity(int x) { return x; }
 
int addmillion(int num) {
for (int i = 0; i < 1000000; i++)
num += i;
return num;
}
 
int main() {
double time;
time = measure([](){ return identity(10); });
// Shove the function into a lambda function.
// Yeah, I couldn't think of any better workaround.
std::cout << "identity(10)\t\t" << time << " milliseconds / " << time / 1000 << " seconds" << std::endl; // Print it
time = measure([](){ return addmillion(1800); });
std::cout << "addmillion(1800)\t" << time << " milliseconds / " << time / 1000 << " seconds" << std::endl;
return 0;
}
</syntaxhighlight>
 
Output:
<pre>
identity(10) 0 milliseconds / 0 seconds
addmillion(1800) 4 milliseconds / 0.004 seconds
</pre>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">
(defn fib []
(map first
Line 763 ⟶ 924:
 
(time (take 100 (fib)))
</syntaxhighlight>
</lang>
 
Output:
Line 773 ⟶ 934:
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 780 ⟶ 941:
0 calls to %EVAL
0 page faults and
2,400,256 bytes consed.</langsyntaxhighlight>
 
(The example output here is from [[SBCL]].)
Line 788 ⟶ 949:
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 797 ⟶ 958:
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 823 ⟶ 984:
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 855 ⟶ 1,016:
Stdout.format("Sum(4) takes {:f6} seconds",timeIt(&sum,4)).newline;
}
</syntaxhighlight>
</lang>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
[[File:DelphiTimerObject.png|frame|none]]
Here is a simple timer object that I use to time different parts of the code, to figure out which parts take the most time and are the best targets for optimization.
 
The object is based on the TPanel, which means the timer can be dropped on a form where it will display timing data whenever you want.
 
The time is controlled by four different commands: '''Reset, Start, Stop'''''Italic text'' and '''Display'''''Italic text''.
 
'''Reset'''. Reset zeros the timer.
'''Start'''. Starts the timer running.
'''Stop'''. Stops the timer.
'''Displays'''. Displays the current cumulative time since the first start.
 
Start and Stop can be moved around the code to control which parts are timed. You can even turn the timer on and off multiple times to messure the combined execution times of multiple different sections of code. You can also move the Start and Stop commands closer and closer together to zoom in on the part of the code that takes the most time to execute.
 
Finally, since the object is based on the TPanel component, the font, colors and layout can be made to look fancy for placement on the status bar of a program.
<syntaxhighlight lang="Delphi">
type TResolution=(rsSeconds,rsMiliSeconds);
 
type TCodeTimer=class(TPanel)
private
FResolution: TResolution;
public
WrkCount,TotCount: longint;
constructor Create(AOwner: TComponent); override;
procedure Reset;
procedure Start;
procedure Stop;
procedure Display;
published
property Resolution: TResolution read FResolution write FResolution default rsMiliSeconds;
end;
 
 
function GetHiResTick: integer;
var C: TLargeInteger;
begin
QueryPerformanceCounter(C);
Result:=C;
end;
 
 
 
 
constructor TCodeTimer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FResolution:=rsMiliSeconds;
end;
 
 
 
procedure TCodeTimer.Reset;
begin
WrkCount:=0;
TotCount:=0;
end;
 
 
procedure TCodeTimer.Start;
begin
WrkCount:=GetHiResTick;
end;
 
 
procedure TCodeTimer.Stop;
begin
TotCount:=TotCount+(GetHiResTick-WrkCount);
end;
 
procedure TCodeTimer.Display;
begin
if FResolution=rsSeconds then Caption:=FloatToStrF(TotCount/1000000,ffFixed,18,3)+' Sec.'
else Caption:=FloatToStrF(TotCount/1000,ffFixed,18,3)+' ms.'
end;
 
</syntaxhighlight>
{{out}}
<pre>
 
</pre>
 
=={{header|E}}==
Line 861 ⟶ 1,106:
{{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 877 ⟶ 1,122:
def finish := threadMX.getCurrentThreadCpuTime()
println(`Counting to $count takes ${(finish-start)//1000000}ms`)
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight lang=easylang>
func fua lim .
# this is interpreted
i = 1
while i <= lim
sum += i
i += 1
.
return sum
.
start = systime
print fua 1e8
print systime - start
#
fastfunc fub lim .
# this is compiled to wasm
i = 1
while i <= lim
sum += i
i += 1
.
return sum
.
start = systime
print fub 1e8
print systime - start
</syntaxhighlight>
 
=={{header|Elena}}==
{{trans|C#}}
ELENA 46.x :
<langsyntaxhighlight lang="elena">import system'calendar;
import system'routines;
import system'threading;
Line 891 ⟶ 1,166:
threadControl.sleep(1000);
new Range(0,10000).filterBy::(x => x.mod:(2) == 0).summarize();
}
Line 903 ⟶ 1,178:
console.printLine("Time elapsed in msec:",(end - start).Milliseconds)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 912 ⟶ 1,187:
{{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|EMal}}==
{{trans|VBA}}
<syntaxhighlight lang="emal">
fun identity = int by int x
int retval = 0
for int i = 0; i < 1000; ++i
retval = x
end
return retval
end
fun sum = int by int num
int t
for int j = 0; j < 1000; ++j
t = num
for int i = 0; i < 10000; i++
t = t + i
end
end
return t
end
int startTime, finishTime
startTime = time()
identity(1)
finishTime = time()
writeLine("1000 times Identity(1) takes " + (finishTime - startTime) + " milliseconds")
startTime = time()
sum(1)
finishTime = time()
writeLine("1000 times Sum(1) takes " + (finishTime - startTime) + " milliseconds")
</syntaxhighlight>
{{out}}
<pre>
1000 times Identity(1) takes 16 milliseconds
1000 times Sum(1) takes 6160 milliseconds
</pre>
 
=={{header|Erlang}}==
Line 928 ⟶ 1,239:
 
'''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 934 ⟶ 1,245:
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 965 ⟶ 1,277:
printf "elapsed %d ms" timer.ElapsedMilliseconds
result
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
{{works with|Factor|0.98}}
<lang factor>[ 10000 iota sum drop ] time</lang>
<syntaxhighlight lang="factor">USING: kernel sequences tools.time ;
Output:
 
Running time: 0.002888635 seconds
[ 10000 <iota> sum drop ] time</syntaxhighlight>
{{out}}
Additional information was collected.
<pre>
dispatch-stats. - Print method dispatch statistics
Running time: 0.002888635 seconds
gc-events. - Print all garbage collection events
 
gc-stats. - Print breakdown of different garbage collection events
Additional information was collected.
gc-summary. - Print aggregate garbage collection statistics
dispatch-stats. - Print method dispatch statistics
gc-events. - Print all garbage collection events
gc-stats. - Print breakdown of different garbage collection events
gc-summary. - Print aggregate garbage collection statistics
</pre>
 
=={{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,009 ⟶ 1,326:
return
end
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function sumToLimit(limit As UInteger) As UInteger
Line 1,030 ⟶ 1,347:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,039 ⟶ 1,356:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Return the time passed in last function
time;</langsyntaxhighlight>
 
=={{header|Go}}==
Line 1,046 ⟶ 1,363:
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,054 ⟶ 1,371:
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,070 ⟶ 1,387:
Count()
}
}</langsyntaxhighlight>
<code>go test</code> varies <code>b.N</code> to get meaningful resolution.
Example:
Line 1,088 ⟶ 1,405:
===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,118 ⟶ 1,435:
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,132 ⟶ 1,449:
 
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,156 ⟶ 1,473:
empty()
count()
}</langsyntaxhighlight>
Output:
<pre>
Line 1,166 ⟶ 1,483:
{{trans|Java}}
===CPU Timing===
<langsyntaxhighlight lang="groovy">import java.lang.management.ManagementFactory
import java.lang.management.ThreadMXBean
 
Line 1,177 ⟶ 1,494:
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,197 ⟶ 1,514:
println "Counting to ${testSize} takes ${measuredTime}ms of ${measurementType}"
}
}</langsyntaxhighlight>
 
Output:
Line 1,208 ⟶ 1,525:
 
=={{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,227 ⟶ 1,544:
-- 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,237 ⟶ 1,554:
 
=={{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,280 ⟶ 1,597:
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,305 ⟶ 1,622:
current size: N/A 0 0 0
Note: static region values should be zero and may not be meaningful.
 
 
=={{header|Insitux}}==
Yes, non-transpiled Insitux really is this slow due to its original and ongoing commission: being shoehorned into a Roblox game.
<syntaxhighlight lang="insitux">(function measure
(let [start result end] [(time) (... . args) (time)])
(str result " took " (- end start) "ms"))
 
(function fib n
(if (< n 2) n
(+ (fib (dec n))
(fib (- n 2)))))
 
(measure fib 35)
;returns "9227465 took 26497ms"</syntaxhighlight>
 
=={{header|Ioke}}==
<langsyntaxhighlight lang="ioke">use("benchmark")
 
func = method((1..50000) reduce(+))
 
Benchmark report(1, 1, func)</langsyntaxhighlight>
 
=={{header|J}}==
Time and space requirements are tested using verbs obtained through the Foreign conjunction (<code>!:</code>). <code>6!:2</code> returns time required for execution, in floating-point measurement of seconds. <code>7!:2</code> returns a measurement of space required to execute. Both receive as input a sentence for execution. The verb <code>timespacex</code> combines these and is available in the standard library.
 
<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.
There's also <code>timex</code> (which is defined as <code>6!:2</code>, but easier for some people to remember) which measures only the execution time. Interestingly, timex typically measures slightly larger times than timespacex. This is likely due to the difference between cold cache (timex) and warm cache (timespacex) -- in timespacex, the modularity of its design means that two runs of the code are performed, once to measure space use the other to measure time use.
 
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' (6!:2,7!:2) '|: 50 50 50 $ i. 50^3'
0.0014169 2.09875e6
0.00488008 3.14829e6
timespacex '|: 50 50 50 $ i. 50^3'
0.0014129 2.09875e6
0.00388519 3.14829e6</lang>
timex '|: 50 50 50 $ i. 50^3'
0.0015032</syntaxhighlight>
 
=={{header|Janet}}==
<syntaxhighlight lang="clojure">(defmacro time
"Print the time it takes to evaluate body to stderr.\n
Evaluates to body."
[body]
(with-syms [$start $val]
~(let [,$start (os/clock)
,$val ,body]
(eprint (- (os/clock) ,$start))
,$val)))
 
(time (os/sleep 0.5))</syntaxhighlight>
{{out}}
<pre>0.500129</pre>
 
=={{header|Java}}==
If you're looking for a quick way to calculate the duration of a few lines of code you can utilize the <code>System.currentTimeMillis</code> method.
<syntaxhighlight lang="java">
long start = System.currentTimeMillis();
/* code you want to time, here */
long duration = System.currentTimeMillis() - start;
</syntaxhighlight>
<br />
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java">import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
 
Line 1,350 ⟶ 1,709:
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,366 ⟶ 1,725:
System.out.println("Counting to 1000000000 takes "+(end-start)+"ms");
 
}</langsyntaxhighlight>
Output:
Counting...
Line 1,376 ⟶ 1,735:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">
function test() {
let n = 0
Line 1,389 ⟶ 1,748:
 
console.log('test() took ' + ((end - start) / 1000) + ' seconds') // test() took 0.001 seconds
</syntaxhighlight>
</lang>
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">clock
1 1023 [dup +] times pop
clock swap -.</syntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia"># v0.6.0
 
function countto(n::Integer)
Line 1,404 ⟶ 1,768:
 
@time countto(10 ^ 5)
@time countto(10 ^ 10)</langsyntaxhighlight>
 
{{out}}
Line 1,418 ⟶ 1,782:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.1.2
// need to enable runtime assertions with JVM -ea option
 
Line 1,441 ⟶ 1,805:
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,454 ⟶ 1,818:
 
=={{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,478 ⟶ 1,842:
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,487 ⟶ 1,851:
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,501 ⟶ 1,865:
t2 = os.clock()
 
print( os.difftime( t2, t1 ) )</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 1,519 ⟶ 1,883:
10000 is Double (default)
 
10000&& is long long (64bit integer)
<lang M2000 Interpreter>
 
255ub is Byte type (unsigned value, 0 to 255)
 
Although parameter limit take the type Byte from the argument passed, the limit-limit converted to integer, so sum and n get type integer, so the loop use integers 16bit. So we use the sumtolimit2. The n-! change sign, and this cause overflow for byte value, so this removed from the sumtolimit2.
 
Function/Module Parameters in M2000 without explicitly assign type take the type from stack of values which a Read statement (which Interpreter insert to code) read from there. This type can't change for the run of module or function. We can define a parameter as variant if we want to allow changes of the type.
 
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Module sumtolimit (limit) {
sum=limit-limit
n=sum
rem print type$(n), type$(sum), type$(limit)
n++
while limit {sum+=limit*n:limit--:n-!}
}
Module sumtolimit2 (limit) {
byte sum, n
n++
while limit {sum++:limit--}
}
Cls ' clear screen
Line 1,545 ⟶ 1,923:
Profiler
sumtolimit 10000
Print TimeCount
Profiler
sumtolimit 10000&&
Print TimeCount
Profiler
sumtolimit 255ub
Print TimeCount
Profiler
sumtolimit2 255ub
Print TimeCount
}
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}}
gives:
<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,579 ⟶ 1,965:
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,593 ⟶ 1,979:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import times, osstrutils
 
proc doWork(x: int) =
var n = x
for i in 0..10000000:
n += i
echo n
template time(statement: untyped): float =
 
template time(s: stmt): expr =
let t0 = cpuTime()
statement
s
cpuTime() - t0
echo "Time = ", time(doWork(100)).formatFloat(ffDecimal, precision = 3), " s"</syntaxhighlight>
 
{{out}}
echo time(doWork(100))</lang>
Compiled in debug mode (no options).
Output:
<pre>2Time = 0.2000000000000000e-01046 s</pre>
 
=={{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,643 ⟶ 2,030:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
%% returns milliseconds
fun {TimeIt Proc}
Line 1,661 ⟶ 2,048:
{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,698 ⟶ 2,085:
'fac2' => sub { fac2(50) },
});
Benchmark::cmpthese($result);</langsyntaxhighlight>
Output:
Benchmark: timing 100000 iterations of fac1, fac2...
Line 1,708 ⟶ 2,095:
 
Example without using Benchmark:
<langsyntaxhighlight lang="perl">sub cpu_time {
my ($user,$system,$cuser,$csystem) = times;
$user + $system
Line 1,733 ⟶ 2,120:
 
printf "Sum(4) takes %f seconds.\n", time_it(\&sum, 4);
# outputs "Sum(4) takes 0.280000 seconds."</langsyntaxhighlight>
 
=={{header|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.
<lang perl6>my $start = now;
(^100000).pick(1000);
say now - $start;</lang>
{{out}}
<pre>0.02301709</pre>
=={{header|Phix}}==
{{libheader|Phix/basics}}
Measures wall-clock time. On Windows the resolution is about 15ms. The elapsed function makes things more human-readable, eg 720 (seconds) => 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>atom t0 = time()
<!--<syntaxhighlight lang="phix">(phixonline)-->
some_procedure()
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
printf(1,"%3.2fs\n",time()-t0)
<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>
printf(1,"%s\n",{elapsed(time()-t0)})</lang>
<span style="color: #008080;">return</span> <span style="color: #000000;">x</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">total</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">num</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100_000_000</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">num</span> <span style="color: #0000FF;">+=</span> <span style="color: #7060A8;">odd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">num</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">time_it</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">fn</span><span style="color: #0000FF;">(</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">funcname</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_routine_info</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)[</span><span style="color: #000000;">4</span><span style="color: #0000FF;">]</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s(4) = %d, taking %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">funcname</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
identity(4) = 4, taking 0s
total(4) = 50000004, taking 6.8s
</pre>
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">def count
for drop endfor
enddef
Line 1,758 ⟶ 2,163:
 
10000000 count
msec t0 - print " seconds" print</langsyntaxhighlight>
 
=={{header|Picat}}==
Picat had some built-in timing functions/predicates:
* <code>time/1</code>: reports the time since start of execution. (The related <code>time2/1</code> also reports the backtracks for CP problems.)
* <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>.
 
<syntaxhighlight lang="picat">import cp.
 
go =>
println("time/1 for 201 queens:"),
time2(once(queens(201,_Q))),
nl,
 
% time1b/1 is a used defined function (using statistics/2)
Time = time1b($once(queens(28,Q2))),
println(Q2),
printf("28-queens took %dms\n", Time),
nl.
 
% N-queens problem.
% N: number of queens to place
% Q: the solution
queens(N, Q) =>
Q=new_list(N),
Q :: 1..N,
all_different(Q),
all_different([$Q[I]-I : I in 1..N]),
all_different([$Q[I]+I : I in 1..N]),
solve([ffd,split],Q).
 
% time1b/1 is a function that returns the time (ms)
time1b(Goal) = T =>
statistics(runtime, _),
call(Goal),
statistics(runtime, [_,T]).</syntaxhighlight>
 
{{out}}
<pre>time/1 for 201 queens:
CPU time 0.049 seconds. Backtracks: 0
 
[1,3,5,23,13,4,21,7,14,26,24,19,6,20,18,28,8,27,2,10,25,17,9,16,12,15,11,22]
28-queens took 0ms</pre>
 
=={{header|PicoLisp}}==
Line 1,766 ⟶ 2,213:
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,775 ⟶ 2,222:
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,788 ⟶ 2,235:
write("Wasted %f CPU seconds calculating primes\n", time_wasted);
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,795 ⟶ 2,242:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">declare (start_time, finish_time) float (18);
 
start_time = secs();
Line 1,809 ⟶ 2,256:
 
/* 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 1,825 ⟶ 2,272:
}
"$((Measure-Command {fun 10000}).TotalSeconds) Seconds"
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
0.820712 Seconds
</pre>
 
 
=={{header|PureBasic}}==
===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 1,856 ⟶ 2,302:
PrintN("and "+Str(cnt)+" are palindromic.")
Print("Press ENTER to exit."): Input()
EndIf</langsyntaxhighlight>
 
Starting timing of a calculation,
Line 1,868 ⟶ 2,314:
 
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 1,881 ⟶ 2,327:
PrintN("and "+Str(cnt)+" are palindromic.")
Print("Press ENTER to exit."): Input()
EndIf</langsyntaxhighlight>
 
Starting timing of a calculation,
Line 1,890 ⟶ 2,336:
 
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 1,919 ⟶ 2,365:
PrintN("and " + Str(cnt) + " are palindromic.")
Print("Press ENTER to exit."): Input()
EndIf</langsyntaxhighlight>
 
Sample output:
Line 1,931 ⟶ 2,377:
 
'''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 1,949 ⟶ 2,395:
from math import pow
def nothing(): pass
def identity(x): return x</langsyntaxhighlight>
 
===Example===
Line 1,961 ⟶ 2,407:
[2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]
using ''qsort()'' from [[Quicksort#Python|Quicksort]]. Timings show that the implementation of ''qsort()'' has quadratic dependence on sequence length ''N'' for already sorted sequences (instead of ''O(N*log(N))'' in average).
 
=={{header|Quackery}}==
 
<code>time</code> returns system time since Unix epoch in microseconds, but is not reliable to the microsecond, so we are using millisecond granularity. Process time is not available.
 
<syntaxhighlight lang="Quackery"> [ time ]'[ do
time swap - 1000 / ] is time: ( --> n )
 
time: [ 0 314159 times 1+ echo ]
cr cr
say "That took about " echo say " milliseconds."</syntaxhighlight>
 
{{out}}
 
<pre>314159
 
That took about 392 milliseconds.
</pre>
 
=={{header|R}}==
R has a built-in function, system.time, to calculate this.
<langsyntaxhighlight Rlang="r"># A task
foo <- function()
{
Line 1,976 ⟶ 2,440:
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" line>my $start = now;
(^100000).pick(1000);
say now - $start;</syntaxhighlight>
{{out}}
<pre>0.02301709</pre>
 
=={{header|Raven}}==
<langsyntaxhighlight Ravenlang="raven">define doId use $x
$x dup * $x /
 
Line 2,012 ⟶ 2,485:
42 "doId" timeFunc
12 2 "doPower" timeFunc
"doSort" timeFunc</langsyntaxhighlight>
{{out}}
<pre>2.193e-05 secs for NULL
Line 2,022 ⟶ 2,495:
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,038 ⟶ 2,511:
<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,064 ⟶ 2,537:
@.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,084 ⟶ 2,557:
<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,110 ⟶ 2,583:
@.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,123 ⟶ 2,596:
elapsedTime = endTime - beginTime
see "Elapsed time = " + elapsedTime + nl
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
In its first versions, RPL did not provide user access to system clock - but advanced users knew which system call can be made on their machine to get it. The following code works on a 1987-manufactured HP-28S, but can crash on older ones and will surely do on other machines. If using a newer model, replace <code>#11CAh SYSEVAL</code> by <code>TICKS</code>, which is a (safe) built-in instruction.
{| class="wikitable"
! RPL code
! Comment
|-
|
#11CAh SYSEVAL → tick
≪ EVAL
#11CAh SYSEVAL tick -
B→R 8192 / 1 FIX RND STD
≫ ≫ '<span style="color:blue">TEVAL</span>' STO
|
<span style="color:blue">TEVAL</span> ''( ≪function≫ -- execution_time )''
Store current system time
Execute function
Measure difference in CPU cycles
convert to seconds, round to one decimal place
|}
{{in}}
<pre>
≪ 1 1000 START NEXT ≫ TEVAL
</pre>
{{out}}
<pre>
1: 6.4
</pre>
Yes, more than 6 seconds to loop 1000 times is quite slow.
 
HP-49+ models have a built-in <code>TEVAL</code> command.
 
=={{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,139 ⟶ 2,645:
 
You can get the total time as a number for later processing like this:
<langsyntaxhighlight lang="ruby">Benchmark.measure { whatever }.total</langsyntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">// 20210224 Rust programming solution
 
use rand::Rng;
use std::time::{Instant};
 
fn custom_function() {
let mut i = 0;
let mut rng = rand::thread_rng();
let n1: f32 = rng.gen();
 
while i < ( 1000000 + 1000000 * ( n1.log10() as i32 ) ) {
i = i + 1;
}
}
 
fn main() {
 
let start = Instant::now();
custom_function();
let duration = start.elapsed();
 
println!("Time elapsed in the custom_function() is : {:?}", duration);
}
</syntaxhighlight>
{{out}}
<pre>
Time elapsed in the custom_function() is : 39.615455ms
</pre>
 
=={{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,149 ⟶ 2,686:
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,201 ⟶ 2,738:
writeln("Identity(4) takes " <& timeIt(identity(4)));
writeln("Sum(4) takes " <& timeIt(sum(4)));
end func;</langsyntaxhighlight>
 
{{out}} of interpreted program:
Line 2,212 ⟶ 2,749:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var benchmark = frequire('Benchmark')
 
func fac_rec(n) {
Line 2,231 ⟶ 2,768:
))
 
benchmark.cmpthese(result)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,243 ⟶ 2,780:
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">
[inform: 2000 factorial] timeToRun.
</syntaxhighlight>
</lang>
 
=={{header|Smalltalk}}==
(Squeak/Pharo/VisualWorks/SmalltalkX)
<syntaxhighlight lang="smalltalk">Time millisecondsToRun: [
<lang smalltalk>
Transcript show: 2000 factorial
Time millisecondsToRun: [
].</syntaxhighlight>
Transcript show: 2000 factorial ].
 
</lang>
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "time_function" )
@( description, "Write a program which uses a timer (with the least " )
@( description, "granularity available on your system) to time how " )
@( description, "long a function takes to execute." )
@( see_also, "http://rosettacode.org/wiki/Time_a_function" );
pragma annotate( author, "Ken O. Burtch" );
pragma license( unrestricted );
 
pragma restriction( no_external_commands );
 
procedure time_function is
 
procedure sample_function( num : in out integer ) is
begin
for i in 1..1000 loop
num := @+1;
end loop;
end sample_function;
 
start_time : calendar.time;
end_time : calendar.time;
seconds : duration;
 
procedure time_sample_function is
sample_param : integer := 4;
begin
start_time := calendar.clock;
sample_function( sample_param );
end_time := calendar.clock;
seconds := end_time - start_time;
end time_sample_function;
 
begin
time_sample_function;
put_line( "sum(4) takes:" & strings.image( seconds ) & " seconds." );
command_line.set_exit_status( 0 );
end time_function;</syntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">fun time_it (action, arg) = let
val timer = Timer.startCPUTimer ()
val _ = action arg
Line 2,261 ⟶ 2,838:
in
Time.+ (#usr times, #sys times)
end</langsyntaxhighlight>
 
===Example===
Line 2,281 ⟶ 2,858:
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,290 ⟶ 2,867:
 
. timer_test 1000
1: 1.01 / 1 = 1.0140</langsyntaxhighlight>
 
 
=={{header|Swift}}==
Line 2,297 ⟶ 2,873:
Using the 2-term ackermann function for demonstration.
 
<langsyntaxhighlight lang="swift">import Foundation
 
public struct TimeResult {
Line 2,352 ⟶ 2,928:
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,362 ⟶ 2,938:
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,368 ⟶ 2,944:
 
puts [time {sum_n 1e6} 100]
puts [time {} 100]</langsyntaxhighlight>
{{out}}
163551.0 microseconds per iteration
Line 2,378 ⟶ 2,954:
 
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,402 ⟶ 2,978:
return %result;
}
</syntaxhighlight>
</lang>
 
{{out|Example}}
<syntaxhighlight lang="torquescript">
<lang TorqueScript>
function exampleFunction(%var1,%var2)
{
Line 2,415 ⟶ 2,991:
==> BENCHMARKING RESULT FOR exampleFunction:
==> 13.257
</syntaxhighlight>
</lang>
 
=={{header|True BASIC}}==
{{trans|QBasic}}
<syntaxhighlight lang="qbasic">SUB cont (n)
LET sum = 0
FOR i = 1 TO n
LET sum = sum+1
NEXT i
END SUB
 
LET timestart = TIME
CALL cont (10000000)
LET timedone = TIME
 
!midnight check:
IF timedone < timestart THEN LET timedone = timedone+86400
LET timeelapsed = (timedone-timestart)*1000
PRINT timeelapsed; "miliseconds."
END</syntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
SECTION test
Line 2,433 ⟶ 3,028:
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,440 ⟶ 3,035:
 
=={{header|UNIX Shell}}==
<syntaxhighlight lang ="bash">$ time sleep 1</langsyntaxhighlight>
 
real 0m1.074s
Line 2,447 ⟶ 3,042:
 
=={{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,473 ⟶ 3,068:
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.
<syntaxhighlight lang="wren">import "./check" for Benchmark
 
Benchmark.run("a function", 100, true) {
for (i in 0..1e7) {}
}</syntaxhighlight>
 
{{out}}
<pre>
Running 'a function' over 100 iteration(s):
-------------------------------------------
Best 191.172 ms
Mean 201.942 ms
Worst 208.049 ms
</pre>
 
=={{header|XPL0}}==
Line 2,497 ⟶ 3,111:
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,503 ⟶ 3,117:
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,511 ⟶ 3,125:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">sub count(n)
local i
Line 2,524 ⟶ 3,138:
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>
 
=={{header|ZX Spectrum Basic}}==
The ZX Spectrum has very little in the way of timing functionality; its best clock is the three-byte FRAMES variable, which starts at zero when the system is turned on and updates every time the ULA refreshes the screen, giving a granularity of one fiftieth of a second. As the system cannot multitask, a difference between the start and end time is as good as we can get; certain actions, most notably operating the system BEEPer, temporarily stop the counter.
 
<syntaxhighlight lang="zxbasic">
1 DEF FN t()=(PEEK 23672+256*PEEK 23673+65536*PEEK 23674)/50
10 LET time=FN t()
20 PRINT ASN 0.5
30 PRINT FN t()-time</syntaxhighlight>
{{out}}
<pre>0.52359878
0.22
 
0 OK, 30:1</pre>
9,476

edits