Time a function: Difference between revisions
m
syntax highlighting fixup automation
(add BQN) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 20:
{{trans|Nim}}
<
V n = x
L(i) 10000000
Line 31:
R time:perf_counter() - start
print(time_func(() -> do_work(100)))</
=={{header|8051 Assembly}}==
Line 47:
is (256^x - 1) * 2^(-p).
<
TSTART EQU 08h ; first register of timer counter
TEND EQU TSTART + TC - 1 ; end register of timer counter
Line 152:
END
</syntaxhighlight>
=={{header|ACL2}}==
<
Output (for Clozure):
Line 165:
=={{header|Action!}}==
<
BYTE RTCLOK2=$14
BYTE PALNTSC=$D014
Line 208:
PrintF("%U ms%E",diffMs)
OD
RETURN</
{{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}}==
<
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;</
===Example===
Identity(4) takes 0.000001117 seconds.
Line 257:
=={{header|Aime}}==
<
identity(integer x)
{
Line 306:
0;
}</
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program fcttime.s */
Line 540:
pop {r2-r4}
bx lr @ return
</syntaxhighlight>
{{out}}
<pre>
Line 572:
=={{header|Arturo}}==
<
print "starting function"
pause 2000
print "function ended"
]</
{{out}}
Line 587:
===System time===
Uses system time, not process time
<
Return
Line 601:
%function%(parameter)
Return ElapsedTime := A_TickCount - StartTime . " milliseconds"
}</
=== Using QueryPerformanceCounter ===
QueryPerformanceCounter allows even more precision:
<
TimeFunction(Function, Parameters*) {
Line 619:
fx() {
Sleep, 1000
}</
=={{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.
<
SUB timed()
SLEEP 7000
Line 632:
timed()
et = TIMER
PRINT st, ", ", et</
{{out}}
Line 640:
=={{header|BASIC}}==
{{works with|QBasic}}
<
timestart = TIMER
Line 648:
'midnight check:
IF timedone < timestart THEN timedone = timedone + 86400
timeelapsed = timedone - timestart</
See also: [[#BBC BASIC|BBC BASIC]], [[#PureBasic|PureBasic]].
=={{header|BASIC256}}==
<
print msec; " milliseconds"
Line 666:
sum += 1
next i
end subroutine</
=={{header|Batch File}}==
Granularity: hundredths of second.
<syntaxhighlight lang="batch file">
@echo off
Setlocal EnableDelayedExpansion
Line 693:
)
goto:eof
</syntaxhighlight>
=={{header|BBC BASIC}}==
<
REM perform processing
lapsed%=TIME-start%</
=={{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
<code>•_timed</code> is a system value that runs <code>F</code> a set number of times and returns the average runtime of the function. Here, since the left argument <code>𝕨</code> is omitted, it is run once.
Line 708:
Here are a few example runs:
<
8.437800000000001e¯05
{0:1;𝕩×𝕊𝕩-1}•_timed 1000
0.000299545</
=={{header|Bracmat}}==
<
= fun funarg t0 ret
. !arg:(?fun.?funarg)
Line 728:
)
& time$(fib.30)
)</
Output:
<pre>1346269.5,141*10E0 s</pre>
Line 738:
<code>CLOCK_PROCESS_CPUTIME_ID</code> is preferred when available (eg. Linux kernel 2.6.12 up), being CPU time used by the current process. (<code>CLOCK_MONOTONIC</code> generally includes CPU time of unrelated processes, and may be drifted by <code>adjtime()</code>.)
<
#include <time.h>
Line 776:
printf("sum (4) takes %lf s\n", time_it(sum, 4));
return 0;
}</
=={{header|C sharp|C#}}==
Line 782:
Using Stopwatch.
<
using System.Linq;
using System.Threading;
Line 803:
Enumerable.Range(1, 10000).Where(x => x % 2 == 0).Sum(); // Sum even numers from 1 to 10000
}
}</
Using DateTime.
<
using System.Linq;
using System.Threading;
Line 827:
Enumerable.Range(1, 10000).Where(x => x % 2 == 0).Sum(); // Sum even numers from 1 to 10000
}
}</
Output:
Line 833:
=={{header|C++}}==
<
#include <iostream>
using namespace std;
Line 855:
cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl;
return 0;
}</
===Example===
Line 862:
=={{header|Clojure}}==
<
(defn fib []
(map first
Line 870:
(time (take 100 (fib)))
</syntaxhighlight>
Output:
Line 880:
Common Lisp provides a standard utility for performance measurement, [http://www.lispworks.com/documentation/HyperSpec/Body/m_time.htm time]:
<
Evaluation took:
0.151 seconds of real time
Line 887:
0 calls to %EVAL
0 page faults and
2,400,256 bytes consed.</
(The example output here is from [[SBCL]].)
Line 895:
The functions [http://www.lispworks.com/documentation/HyperSpec/Body/f_get__1.htm get-internal-run-time] and [http://www.lispworks.com/documentation/HyperSpec/Body/f_get_in.htm get-internal-real-time] may be used to get time information programmatically, with at least one-second granularity (and usually more). Here is a function which uses them to measure the time taken for one execution of a provided function:
<
(let ((real-base (get-internal-real-time))
(run-base (get-internal-run-time)))
Line 904:
CL-USER> (timings (lambda () (reduce #'+ (make-list 100000 :initial-element 1))))
17/500
7/250</
=={{header|D}}==
<
int identity(int x) {
Line 930:
writefln("identity(4) takes %f6 seconds.", timeIt(&identity, 4));
writefln("sum(4) takes %f seconds.", timeIt(&sum, 4));
}</
Output:<pre>identity(4) takes 0.0000016 seconds.
sum(4) takes 0.522065 seconds.</pre>
===Using Tango===
<syntaxhighlight lang="d">
import tango.io.Stdout;
import tango.time.Clock;
Line 962:
Stdout.format("Sum(4) takes {:f6} seconds",timeIt(&sum,4)).newline;
}
</syntaxhighlight>
=={{header|E}}==
Line 968:
{{trans|Java}} — E has no ''standardized'' facility for CPU time measurement; this {{works with|E-on-Java}}.
<
println("Counting...")
for _ in 1..x {}
Line 984:
def finish := threadMX.getCurrentThreadCpuTime()
println(`Counting to $count takes ${(finish-start)//1000000}ms`)
}</
=={{header|Elena}}==
{{trans|C#}}
ELENA 4.x :
<
import system'routines;
import system'threading;
Line 1,011:
console.printLine("Time elapsed in msec:",(end - start).Milliseconds)
}</
{{out}}
<pre>
Line 1,020:
{{trans|Erlang}}
'''tc/1'''
<
{236000, :ok}</
'''tc/2'''
<
{2300000, :ok}</
'''tc/3'''
<
{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, ...]}</
=={{header|Erlang}}==
Line 1,036:
'''tc/1''' takes a 0-arity function and executes it:
<
5> {Time,Result} = timer:tc(fun () -> lists:foreach(fun(X) -> X*X end, lists:seq(1,100000)) end).
{226391,ok}
Line 1,042:
0.226391
7> % Time is in microseconds.
</syntaxhighlight>
'''tc/2''' takes an n-arity function and its arguments:
<
9> timer:tc(fun (X) -> lists:foreach(fun(Y) -> Y*Y end, lists:seq(1,X)) end, [1000000]).
{2293844,ok}
</syntaxhighlight>
'''tc/3''' takes a module name, function name and the list of arguments to the function:
<
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>
=={{header|Euphoria}}==
<
t = time()
some_procedure()
t = time() - t
printf(1,"Elapsed %f seconds.\n",t)</
=={{header|F Sharp|F#}}==
The .Net framework provides a Stopwatch class which provides a performance counter.
<
open System.Diagnostics
let myfunc data =
Line 1,074:
printf "elapsed %d ms" timer.ElapsedMilliseconds
result
</syntaxhighlight>
=={{header|Factor}}==
{{works with|Factor|0.98}}
<
[ 10000 <iota> sum drop ] time</
{{out}}
<pre>
Line 1,094:
=={{header|Forth}}==
{{works with|GNU Forth}}
<
utime 2>R ' EXECUTE
utime 2R> D-
<# # # # # # # [CHAR] . HOLD #S #> TYPE ." seconds" ;
1000 time: MS \ 1.000081 seconds ok</
=={{header|Fortran}}==
{{works with|Gfortran}} version 4.4.5 (Debian 4.4.5-8) on x86_64-linux-gnu
<
c The subroutine to analyze
subroutine do_something()
Line 1,123:
return
end
</syntaxhighlight>
=={{header|FreeBASIC}}==
<
Function sumToLimit(limit As UInteger) As UInteger
Line 1,144:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,153:
=={{header|GAP}}==
<
time;</
=={{header|Go}}==
Line 1,160:
The Go command line tool <code>go test</code> includes [http://golang.org/pkg/testing/#hdr-Benchmarks benchmarking support].
Given a package with functions:
<
func Empty() {}
Line 1,168:
for i := 0; i < 1e6; i++ {
}
}</
the following code, placed in a file whose name ends in <tt>_test.go</tt>, will time them:
<
import "testing"
Line 1,184:
Count()
}
}</
<code>go test</code> varies <code>b.N</code> to get meaningful resolution.
Example:
Line 1,202:
===testing.Benchmark===
The benchmarking features of the <code>testing</code> package are exported for use within a Go program.
<
import (
Line 1,232:
fmt.Printf("Empty: %12.4f\n", float64(e.T.Nanoseconds())/float64(e.N))
fmt.Printf("Count: %12.4f\n", float64(c.T.Nanoseconds())/float64(c.N))
}</
{{out}}
<pre>
Line 1,246:
As the first line of the function you wish to time, use <tt>defer</tt> with an argument of <tt>time.Now()</tt> to print the elapsed time to the return of any function. For example, define the function <tt>from</tt> as shown below. It works because defer evaluates its function's arguments at the time the function is deferred, so the current time gets captured at the point of the defer. When the function containing the defer returns, the deferred <tt>from</tt> function runs, computes the elapsed time as a <tt>time.Duration</tt>, and prints it with standard formatting, which adds a nicely scaled unit suffix.
<
import (
Line 1,270:
empty()
count()
}</
Output:
<pre>
Line 1,280:
{{trans|Java}}
===CPU Timing===
<
import java.lang.management.ThreadMXBean
Line 1,291:
c.call()
(threadMX.currentThreadCpuTime - start)/1000000
}</
===Wall Clock Timing===
<
def start = System.currentTimeMillis()
c.call()
System.currentTimeMillis() - start
}</
Test:
<
long i = 0; while(i < n) { i += 1L }
}
Line 1,311:
println "Counting to ${testSize} takes ${measuredTime}ms of ${measurementType}"
}
}</
Output:
Line 1,322:
=={{header|Halon}}==
<
sleep(1);
echo uptime() - $t;</
=={{header|Haskell}}==
<
-- We assume the function we are timing is an IO monad computation
Line 1,341:
-- Version for use with evaluating regular non-monadic functions
timeIt_ :: (Fractional c) => (a -> b) -> a -> IO c
timeIt_ f = timeIt ((`seq` return ()) . f)</
===Example===
Line 1,351:
=={{header|HicEst}}==
<
SYSTEM(WAIT = 1234) ! wait 1234 milliseconds
t_end = TIME()
WRITE(StatusBar) t_end - t_start, " seconds"</
=={{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.
<
local gcol,alloc,used,size,runtime,header,x,i
Line 1,394:
write("Note: static region values should be zero and may not be meaningful.")
return
end</
Sample usage:<
timef(perfectnumbers)
end
procedure perfectnumbers()
...</
Sample output (from the [[Perfect_numbers#Icon_and_Unicon|Perfect Numbers]] task):
Line 1,421:
=={{header|Ioke}}==
<
func = method((1..50000) reduce(+))
Benchmark report(1, 1, func)</
=={{header|J}}==
Line 1,431:
<br>When the [http://www.jsoftware.com/help/dictionary/dmcapdot.htm Memoize] feature or similar techniques are used, execution time and space can both be affected by prior calculations.
===Example===
<
0.00488008 3.14829e6
timespacex '|: 50 50 50 $ i. 50^3'
0.00388519 3.14829e6</
=={{header|Janet}}==
<
"Print the time it takes to evaluate body to stderr.\n
Evaluates to body."
Line 1,446:
,$val)))
(time (os/sleep 0.5))</
{{out}}
<pre>0.500129</pre>
Line 1,452:
=={{header|Java}}==
{{works with|Java|1.5+}}
<
import java.lang.management.ThreadMXBean;
Line 1,478:
System.out.println("Done!");
}
}</
Measures real time rather than CPU time:
{{works with|Java|(all versions)}}
<
long start, end;
start = System.currentTimeMillis();
Line 1,494:
System.out.println("Counting to 1000000000 takes "+(end-start)+"ms");
}</
Output:
Counting...
Line 1,504:
=={{header|JavaScript}}==
<
function test() {
let n = 0
Line 1,517:
console.log('test() took ' + ((end - start) / 1000) + ' seconds') // test() took 0.001 seconds
</syntaxhighlight>
=={{header|Julia}}==
<
function countto(n::Integer)
Line 1,532:
@time countto(10 ^ 5)
@time countto(10 ^ 10)</
{{out}}
Line 1,546:
=={{header|Kotlin}}==
{{trans|Java}}
<
// need to enable runtime assertions with JVM -ea option
Line 1,569:
println("Counting to $count takes ${(end-start)/1000000}ms")
}
}</
This is a typical result (sometimes the second figure is only about 1400ms - no idea why)
{{out}}
Line 1,582:
=={{header|Lasso}}==
<
loop(100000) => {
'nothing is outout because no autocollect'
}
'time for 100,000 loop repititions: '+(micros - #start)+' microseconds'</
=={{header|Lingo}}==
<
repeat with i = 1 to 1000000
x = sqrt(log(i))
end repeat
end</
<
testFunc()
ms = _system.milliseconds - ms
put "Execution time in ms:" && ms
-- "Execution time in ms: 983"</
=={{header|Logo}}==
Line 1,606:
This is not an ideal method; Logo does not expose a timer (except for the WAIT command) so we use the Unix "date" command to get a second timer.
<
output first first shell "|date +%s|
end
Line 1,615:
end
elapsed [wait 300] ; 5 seconds elapsed</
=={{header|Lua}}==
<
for i = 1, 10000000 do
local s = math.log( i )
Line 1,629:
t2 = os.clock()
print( os.difftime( t2, t1 ) )</
=={{header|M2000 Interpreter}}==
Line 1,647:
10000 is Double (default)
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Module sumtolimit (limit) {
Line 1,676:
}
Checkit
</syntaxhighlight>
=={{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.
<
<
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang
where x is an operation. Example calculating a million digits of Sqrt[3]:
<
{{out}}
<
First elements if the time in seconds, second elements if the result from the operation. Note that I truncated the result.
=={{header|Maxima}}==
<
/* First solution, call the time function with an output line number, it gives the time taken to compute that line.
Line 1,707:
f(24);
Evaluation took 0.9400 seconds (0.9400 elapsed)
46368</
=={{header|MiniScript}}==
<
for i in range(1,100000)
end for
duration = time - start
print "Process took " + duration + " seconds"</
{{out}}
<pre>
Line 1,721:
=={{header|Nim}}==
<
proc doWork(x: int) =
Line 1,733:
cpuTime() - t0
echo "Time = ", time(doWork(100)).formatFloat(ffDecimal, precision = 3), " s"</
{{out}}
Line 1,740:
=={{header|OCaml}}==
<
let start_time = Sys.time () in
ignore (action arg);
let finish_time = Sys.time () in
finish_time -. start_time</
===Example===
Line 1,772:
=={{header|Oz}}==
<
%% returns milliseconds
fun {TimeIt Proc}
Line 1,790:
{FoldL {List.number 1 1000000 1} Number.'+' 4 _}
end}
}</
=={{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.
<
foo();
gettime();
}</
Alternate version:
{{works with|PARI/GP|2.6.2+}}
<
my(start=getabstime());
foo();
getabstime()-start;
}</
=={{header|Perl}}==
Example of using the built-in Benchmark core module - it compares two versions of recursive factorial functions:
<
use Memoize;
Line 1,827:
'fac2' => sub { fac2(50) },
});
Benchmark::cmpthese($result);</
Output:
Benchmark: timing 100000 iterations of fac1, fac2...
Line 1,837:
Example without using Benchmark:
<
my ($user,$system,$cuser,$csystem) = times;
$user + $system
Line 1,862:
printf "Sum(4) takes %f seconds.\n", time_it(\&sum, 4);
# outputs "Sum(4) takes 0.280000 seconds."</
=={{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".
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
Line 1,889:
<span style="color: #000000;">time_it</span><span style="color: #0000FF;">(</span><span style="color: #000000;">identity</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">time_it</span><span style="color: #0000FF;">(</span><span style="color: #000000;">total</span><span style="color: #0000FF;">)</span>
<!--</
{{out}}
<pre>
Line 1,897:
=={{header|Phixmonti}}==
<
for drop endfor
enddef
Line 1,905:
10000000 count
msec t0 - print " seconds" print</
=={{header|Picat}}==
Line 1,912:
* <code>statistics(runtime,[ProgTime,LastTime])</code>: <code>ProgTime</code> is the ms since program started, <code>LastTime</code> is the ms since last call to <code>statistics(runtime,_)</code>. It can be used to create user defined time predicates/functions, as show in <code>time1b/1</code>.
<
go =>
Line 1,940:
statistics(runtime, _),
call(Goal),
statistics(runtime, [_,T]).</
{{out}}
Line 1,955:
There is another function, '[http://software-lab.de/doc/refT.html#tick tick]', which
also measures user time, and is used by the profiling tools.
<
0.080 sec
-> 12</
=={{header|Pike}}==
Line 1,964:
function gauge(), but it could also be done manually with
gethrvtime() in ms or ns resolution.
<syntaxhighlight lang="pike">
void get_some_primes()
{
Line 1,977:
write("Wasted %f CPU seconds calculating primes\n", time_wasted);
}
</syntaxhighlight>
{{Out}}
<pre>
Line 1,984:
=={{header|PL/I}}==
<
start_time = secs();
Line 1,998:
/* Note: using the SECS function takes into account the clock */
/* going past midnight. */</
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function fun($n){
$res = 0
Line 2,014:
}
"$((Measure-Command {fun 10000}).TotalSeconds) Seconds"
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 2,023:
===Built in timer===
This version uses the built in timer, on Windows it has an accuracy of ~10-15 msec.
<
Protected i, palindromic, String$
For i=0 To Limit
Line 2,044:
PrintN("and "+Str(cnt)+" are palindromic.")
Print("Press ENTER to exit."): Input()
EndIf</
Starting timing of a calculation,
Line 2,056:
This version uses a hi-res timer, but it is Windows only.
<
Define Timed.f, cnt
PrintN("Starting timing of a calculation,")
Line 2,069:
PrintN("and "+Str(cnt)+" are palindromic.")
Print("Press ENTER to exit."): Input()
EndIf</
Starting timing of a calculation,
Line 2,078:
This version still relies on the Windows API but does not make use of any additional libraries.
<
Static maxfreq.q
Protected T.q
Line 2,107:
PrintN("and " + Str(cnt) + " are palindromic.")
Print("Press ENTER to exit."): Input()
EndIf</
Sample output:
Line 2,119:
'''Note:''' There is an overhead in executing a function that does nothing.
<
def usec(function, arguments):
modname, funcname = __name__, function.__name__
Line 2,137:
from math import pow
def nothing(): pass
def identity(x): return x</
===Example===
Line 2,152:
=={{header|R}}==
R has a built-in function, system.time, to calculate this.
<
foo <- function()
{
Line 2,164:
timer <- system.time(foo())
# Extract the processing time
timer["user.self"]</
For a breakdown of processing time by function, there is Rprof.
<
foo()
Rprof(NULL)
summaryRprof()</
=={{header|Racket}}==
<
#lang racket
(define (fact n) (if (zero? n) 1 (* n (fact (sub1 n)))))
(time (fact 5000))
</syntaxhighlight>
=={{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"
(^100000).pick(1000);
say now - $start;</
{{out}}
<pre>0.02301709</pre>
=={{header|Raven}}==
<
$x dup * $x /
Line 2,209:
42 "doId" timeFunc
12 2 "doPower" timeFunc
"doSort" timeFunc</
{{out}}
<pre>2.193e-05 secs for NULL
Line 2,219:
Retro has a '''time''' function returning the current time in seconds. This can be used to build a simple timing function:
<
: test 20000 [ putn space ] iterd ;
&test .runtime</
Finer measurements are not possible with the standard implementation.
Line 2,235:
<br>there's a way to easily query the host (VM/CP) to indicate how much ''true'' CPU time was used by
<br>(normally) your own userID. The result can then be placed into a REXX variable (as an option).
<
arg reps . /*obtain an optional argument from C.L.*/
if reps=='' then reps=100000 /*Not specified? No, then use default.*/
Line 2,261:
@.j=random() date() time() digits() fuzz() form() xrange() queued()
end /*j*/
return j-1</
'''output''' when using a personal computer built in the 20th century:
<pre>
Line 2,281:
<br>being measured is essentially the same as the wall clock time (duration) of the function execution; the
<br>overhead of the invocation is minimal compared to the overall time used.
<
arg reps . /*obtain an optional argument from C.L.*/
if reps=='' then reps=100000 /*Not specified? No, then use default.*/
Line 2,307:
@.j=random() date() time() digits() fuzz() form() xrange() queued()
end /*j*/
return j-1</
'''output''' is essentially identical to the previous examples.
<br><br>
=={{header|Ring}}==
<
beginTime = TimeList()[13]
for n = 1 to 10000000
Line 2,320:
elapsedTime = endTime - beginTime
see "Elapsed time = " + elapsedTime + nl
</syntaxhighlight>
=={{header|Ruby}}==
Ruby's Benchmark module provides a way to generate nice reports (numbers are in seconds):
<
Benchmark.bm(8) do |x|
x.report("nothing:") { }
x.report("sum:") { (1..1_000_000).inject(4) {|sum, x| sum + x} }
end</
Output:
user system total real
Line 2,336:
You can get the total time as a number for later processing like this:
<
=={{header|Rust}}==
<
use rand::Rng;
Line 2,363:
println!("Time elapsed in the custom_function() is : {:?}", duration);
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,371:
=={{header|Scala}}==
Define a <code>time</code> function that returns the elapsed time (in ms) to execute a block of code.
<
def time(f: => Unit)={
val s = System.currentTimeMillis
Line 2,377:
System.currentTimeMillis - s
}
</syntaxhighlight>
Can be called with a code block:
<
println(time {
for(i <- 1 to 10000000) {}
})
</syntaxhighlight>
Or with a function:
<
def count(i:Int) = for(j <- 1 to i){}
println(time (count(10000000)))
</syntaxhighlight>
=={{header|Scheme}}==
<syntaxhighlight lang
=={{header|Seed7}}==
<
include "time.s7i";
include "duration.s7i";
Line 2,429:
writeln("Identity(4) takes " <& timeIt(identity(4)));
writeln("Sum(4) takes " <& timeIt(sum(4)));
end func;</
{{out}} of interpreted program:
Line 2,440:
=={{header|Sidef}}==
<
func fac_rec(n) {
Line 2,459:
))
benchmark.cmpthese(result)</
{{out}}
<pre>
Line 2,471:
=={{header|Slate}}==
<
[inform: 2000 factorial] timeToRun.
</syntaxhighlight>
=={{header|Smalltalk}}==
(Squeak/Pharo/VisualWorks/SmalltalkX)
<
Transcript show: 2000 factorial
].</
=={{header|Standard ML}}==
<
val timer = Timer.startCPUTimer ()
val _ = action arg
Line 2,488:
in
Time.+ (#usr times, #sys times)
end</
===Example===
Line 2,508:
Stata can track up to 100 timers. See '''[http://www.stata.com/help.cgi?timer timer]''' in Stata help.
<
timer clear 1
timer on 1
Line 2,517:
. timer_test 1000
1: 1.01 / 1 = 1.0140</
=={{header|Swift}}==
Line 2,523:
Using the 2-term ackermann function for demonstration.
<
public struct TimeResult {
Line 2,578:
let (n2, t2) = ClockTimer.time { ackermann(m: 4, n: 1) }
print("Took \(t2.duration)s to calculate ackermann(m: 4, n: 1) = \(n2)")</
{{out}}
Line 2,588:
The Tcl <code>time</code> command returns the real time elapsed
averaged over a number of iterations.
<
for {set i 1; set sum 0.0} {$i <= $n} {incr i} {set sum [expr {$sum + $i}]}
return [expr {wide($sum)}]
Line 2,594:
puts [time {sum_n 1e6} 100]
puts [time {} 100]</
{{out}}
163551.0 microseconds per iteration
Line 2,604:
Returns average time elapsed from many iterations.
<syntaxhighlight lang="torquescript">
function benchmark(%times,%function,%a,%b,%c,%d,%e,%f,%g,%h,%i,%j,%k,%l,%m,%n,%o)
{
Line 2,628:
return %result;
}
</syntaxhighlight>
{{out|Example}}
<syntaxhighlight lang="torquescript">
function exampleFunction(%var1,%var2)
{
Line 2,641:
==> BENCHMARKING RESULT FOR exampleFunction:
==> 13.257
</syntaxhighlight>
=={{header|True BASIC}}==
{{trans|QBasic}}
<
LET sum = 0
FOR i = 1 TO n
Line 2,660:
LET timeelapsed = (timedone-timestart)*1000
PRINT timeelapsed; "miliseconds."
END</
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
SECTION test
Line 2,678:
PRINT "'test' ends at ",time_end
PRINT "'test' takes ",interval," seconds"
</syntaxhighlight>
{{out}}
'test' start at 2011-01-15 14:38:22
Line 2,685:
=={{header|UNIX Shell}}==
<syntaxhighlight lang
real 0m1.074s
Line 2,692:
=={{header|VBA}}==
<
Private Function identity(x As Long) As Long
For j = 0 To 1000
Line 2,718:
finis_time = GetTickCount
Debug.Print "1000 times Sum(1) takes "; (finis_time - start_time); " milliseconds"
End Sub</
1000 times Sum(1) takes 296 seconds</pre>
=={{header|Wart}}==
<
30000/1000000 # in microseconds
=> 2</
=={{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.
<
Benchmark.run("a function", 100, true) {
for (i in 0..1e7) {}
}</
{{out}}
Line 2,761:
and thus the two values can be out of sync.
<
int T0, T1, I;
[T0:= GetTime;
Line 2,767:
T1:= GetTime;
IntOut(0, T1-T0); Text(0, " microseconds^M^J");
]</
{{out|Example output}} for a Duron 850 running DOS 5.0:
Line 2,775:
=={{header|Yabasic}}==
<
local i
Line 2,788:
t0 = peek("millisrunning")
count(10000000)
print peek("millisrunning")-t0, " milliseconds"</
=={{header|zkl}}==
In order to be as OS independent as possible, only system time is available.
<
{{out}}
<pre>3</pre>
|