Time a function: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(27 intermediate revisions by 18 users not shown)
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}}==
<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 677 ⟶ 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 698 ⟶ 728:
)
& time$(fib.30)
)</langsyntaxhighlight>
Output:
<pre>1346269.5,141*10E0 s</pre>
Line 708 ⟶ 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 746 ⟶ 776:
printf("sum (4) takes %lf s\n", time_it(sum, 4));
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
Line 752 ⟶ 782:
Using Stopwatch.
 
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Threading;
Line 773 ⟶ 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 797 ⟶ 827:
Enumerable.Range(1, 10000).Where(x => x % 2 == 0).Sum(); // Sum even numers from 1 to 10000
}
}</langsyntaxhighlight>
 
Output:
Line 803 ⟶ 833:
 
=={{header|C++}}==
===Using <code>ctime</code>===
<lang cpp>#include <ctime>
<syntaxhighlight lang="cpp">#include <ctime>
#include <iostream>
using namespace std;
Line 825 ⟶ 856:
cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl;
return 0;
}</langsyntaxhighlight>
 
Output:
===Example===
<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 840 ⟶ 924:
 
(time (take 100 (fib)))
</syntaxhighlight>
</lang>
 
Output:
Line 850 ⟶ 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 857 ⟶ 941:
0 calls to %EVAL
0 page faults and
2,400,256 bytes consed.</langsyntaxhighlight>
 
(The example output here is from [[SBCL]].)
Line 865 ⟶ 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 874 ⟶ 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 900 ⟶ 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 932 ⟶ 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 938 ⟶ 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 954 ⟶ 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 969 ⟶ 1,166:
threadControl.sleep(1000);
new Range(0,10000).filterBy::(x => x.mod:(2) == 0).summarize();
}
Line 981 ⟶ 1,178:
console.printLine("Time elapsed in msec:",(end - start).Milliseconds)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 990 ⟶ 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 1,006 ⟶ 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 1,012 ⟶ 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 1,044 ⟶ 1,277:
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,064 ⟶ 1,297:
=={{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,093 ⟶ 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,114 ⟶ 1,347:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,123 ⟶ 1,356:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Return the time passed in last function
time;</langsyntaxhighlight>
 
=={{header|Go}}==
Line 1,130 ⟶ 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,138 ⟶ 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,154 ⟶ 1,387:
Count()
}
}</langsyntaxhighlight>
<code>go test</code> varies <code>b.N</code> to get meaningful resolution.
Example:
Line 1,172 ⟶ 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,202 ⟶ 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,216 ⟶ 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,240 ⟶ 1,473:
empty()
count()
}</langsyntaxhighlight>
Output:
<pre>
Line 1,250 ⟶ 1,483:
{{trans|Java}}
===CPU Timing===
<langsyntaxhighlight lang="groovy">import java.lang.management.ManagementFactory
import java.lang.management.ThreadMXBean
 
Line 1,261 ⟶ 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,281 ⟶ 1,514:
println "Counting to ${testSize} takes ${measuredTime}ms of ${measurementType}"
}
}</langsyntaxhighlight>
 
Output:
Line 1,292 ⟶ 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,311 ⟶ 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,321 ⟶ 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,364 ⟶ 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,389 ⟶ 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}}==
<langsyntaxhighlight Clojurelang="clojure">(defmacro time
"Print the time it takes to evaluate body to stderr.\n
Evaluates to body."
Line 1,416 ⟶ 1,670:
,$val)))
 
(time (os/sleep 0.5))</langsyntaxhighlight>
{{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,448 ⟶ 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,464 ⟶ 1,725:
System.out.println("Counting to 1000000000 takes "+(end-start)+"ms");
 
}</langsyntaxhighlight>
Output:
Counting...
Line 1,474 ⟶ 1,735:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">
function test() {
let n = 0
Line 1,487 ⟶ 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,502 ⟶ 1,768:
 
@time countto(10 ^ 5)
@time countto(10 ^ 10)</langsyntaxhighlight>
 
{{out}}
Line 1,516 ⟶ 1,782:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.1.2
// need to enable runtime assertions with JVM -ea option
 
Line 1,539 ⟶ 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,552 ⟶ 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,576 ⟶ 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,585 ⟶ 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,599 ⟶ 1,865:
t2 = os.clock()
 
print( os.difftime( t2, t1 ) )</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 1,617 ⟶ 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,643 ⟶ 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}}
<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,677 ⟶ 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,691 ⟶ 1,979:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import times, strutils
proc doWork(x: int) =
Line 1,703 ⟶ 1,991:
cpuTime() - t0
echo "Time = ", time(doWork(100)).formatFloat(ffDecimal, precision = 3), " s"</langsyntaxhighlight>
 
{{out}}
Line 1,710 ⟶ 1,998:
 
=={{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,742 ⟶ 2,030:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
%% returns milliseconds
fun {TimeIt Proc}
Line 1,760 ⟶ 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,797 ⟶ 2,085:
'fac2' => sub { fac2(50) },
});
Benchmark::cmpthese($result);</langsyntaxhighlight>
Output:
Benchmark: timing 100000 iterations of fac1, fac2...
Line 1,807 ⟶ 2,095:
 
Example without using Benchmark:
<langsyntaxhighlight lang="perl">sub cpu_time {
my ($user,$system,$cuser,$csystem) = times;
$user + $system
Line 1,832 ⟶ 2,120:
 
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,859 ⟶ 2,147:
<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,867 ⟶ 2,155:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">def count
for drop endfor
enddef
Line 1,875 ⟶ 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>.
 
<langsyntaxhighlight Picatlang="picat">import cp.
 
go =>
Line 1,910 ⟶ 2,198:
statistics(runtime, _),
call(Goal),
statistics(runtime, [_,T]).</langsyntaxhighlight>
 
{{out}}
Line 1,925 ⟶ 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,934 ⟶ 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,947 ⟶ 2,235:
write("Wasted %f CPU seconds calculating primes\n", time_wasted);
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,954 ⟶ 2,242:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">declare (start_time, finish_time) float (18);
 
start_time = secs();
Line 1,968 ⟶ 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,984 ⟶ 2,272:
}
"$((Measure-Command {fun 10000}).TotalSeconds) Seconds"
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 1,993 ⟶ 2,281:
===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,014 ⟶ 2,302:
PrintN("and "+Str(cnt)+" are palindromic.")
Print("Press ENTER to exit."): Input()
EndIf</langsyntaxhighlight>
 
Starting timing of a calculation,
Line 2,026 ⟶ 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 2,039 ⟶ 2,327:
PrintN("and "+Str(cnt)+" are palindromic.")
Print("Press ENTER to exit."): Input()
EndIf</langsyntaxhighlight>
 
Starting timing of a calculation,
Line 2,048 ⟶ 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 2,077 ⟶ 2,365:
PrintN("and " + Str(cnt) + " are palindromic.")
Print("Press ENTER to exit."): Input()
EndIf</langsyntaxhighlight>
 
Sample output:
Line 2,089 ⟶ 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 2,107 ⟶ 2,395:
from math import pow
def nothing(): pass
def identity(x): return x</langsyntaxhighlight>
 
===Example===
Line 2,119 ⟶ 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 2,134 ⟶ 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" 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,179 ⟶ 2,485:
42 "doId" timeFunc
12 2 "doPower" timeFunc
"doSort" timeFunc</langsyntaxhighlight>
{{out}}
<pre>2.193e-05 secs for NULL
Line 2,189 ⟶ 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,205 ⟶ 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,231 ⟶ 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,251 ⟶ 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,277 ⟶ 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,290 ⟶ 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,306 ⟶ 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}}==
<langsyntaxhighlight lang="rust">// 20210224 Rust programming solution
 
use rand::Rng;
Line 2,333 ⟶ 2,672:
println!("Time elapsed in the custom_function() is : {:?}", duration);
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,341 ⟶ 2,680:
=={{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,347 ⟶ 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,399 ⟶ 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,410 ⟶ 2,749:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var benchmark = frequire('Benchmark')
 
func fac_rec(n) {
Line 2,429 ⟶ 2,768:
))
 
benchmark.cmpthese(result)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,441 ⟶ 2,780:
 
=={{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|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,458 ⟶ 2,838:
in
Time.+ (#usr times, #sys times)
end</langsyntaxhighlight>
 
===Example===
Line 2,478 ⟶ 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,487 ⟶ 2,867:
 
. timer_test 1000
1: 1.01 / 1 = 1.0140</langsyntaxhighlight>
 
=={{header|Swift}}==
Line 2,493 ⟶ 2,873:
Using the 2-term ackermann function for demonstration.
 
<langsyntaxhighlight lang="swift">import Foundation
 
public struct TimeResult {
Line 2,548 ⟶ 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,558 ⟶ 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,564 ⟶ 2,944:
 
puts [time {sum_n 1e6} 100]
puts [time {} 100]</langsyntaxhighlight>
{{out}}
163551.0 microseconds per iteration
Line 2,574 ⟶ 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,598 ⟶ 2,978:
return %result;
}
</syntaxhighlight>
</lang>
 
{{out|Example}}
<syntaxhighlight lang="torquescript">
<lang TorqueScript>
function exampleFunction(%var1,%var2)
{
Line 2,611 ⟶ 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,629 ⟶ 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,636 ⟶ 3,035:
 
=={{header|UNIX Shell}}==
<syntaxhighlight lang ="bash">$ time sleep 1</langsyntaxhighlight>
 
real 0m1.074s
Line 2,643 ⟶ 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,669 ⟶ 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.
<langsyntaxhighlight ecmascriptlang="wren">import "./check" for Benchmark
 
Benchmark.run("a function", 100, true) {
for (i in 0..1e7) {}
}</langsyntaxhighlight>
 
{{out}}
Line 2,712 ⟶ 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,718 ⟶ 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,726 ⟶ 3,125:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">sub count(n)
local i
Line 2,739 ⟶ 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,482

edits