Rate counter: Difference between revisions

Added Chipmunk Basic
(Added Wren)
(Added Chipmunk Basic)
 
(17 intermediate revisions by 14 users not shown)
Line 11:
 
'''See also:''' [[System time]], [[Time a function]]
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
DEFINE PTR="CARD"
 
CARD FUNC GetFrame()
BYTE RTCLOK1=$13,RTCLOK2=$14
CARD res
BYTE lsb=res,msb=res+1
 
lsb=RTCLOK2
msb=RTCLOK1
RETURN (res)
 
CARD FUNC FramesToMs(CARD frames)
BYTE PALNTSC=$D014
CARD res
 
IF PALNTSC=15 THEN
res=frames*60
ELSE
res=frames*50
FI
RETURN (res)
 
CARD FUNC ItersPerSecond(CARD timeMs,iters)
REAL rTime,rIters,r1000,tmp
CARD res
 
IntToReal(timeMs,tmp)
IntToReal(iters,rIters)
IntToReal(1000,r1000)
RealDiv(tmp,r1000,rTime)
RealDiv(rIters,rTime,tmp)
res=RealToInt(tmp)
RETURN (res)
 
;jump addr is stored in X and A registers
PROC Action=*(PTR jumpAddr)
DEFINE STX="$8E"
DEFINE STA="$8D"
DEFINE JSR="$20"
DEFINE RTS="$60"
[STX Action+8
STA Action+7
JSR $00 $00
RTS]
 
PROC Benchmark(PTR ARRAY actions,times BYTE count CARD iters)
BYTE i
CARD j,beg,end,diff,diffMs
PTR act
 
FOR i=0 TO count-1
DO
act=actions(i)
beg=GetFrame()
FOR j=0 TO iters-1
DO
Action(act)
OD
end=GetFrame()
diff=end-beg
times(i)=FramesToMs(diff)
OD
RETURN
 
PROC Action1()
RETURN
 
PROC Action2()
INT a=[12345],b=[23456],c
 
c=a+b
RETURN
 
PROC Action3()
INT i=[12345]
CHAR ARRAY s(6)
 
StrI(i,s)
RETURN
 
PROC Main()
DEFINE COUNT="3"
DEFINE ITERS="10000"
PTR ARRAY actions(COUNT)
CARD ARRAY times(COUNT),prec,rate
BYTE i
 
Put(125) PutE() ;clear the screen
prec=FramesToMs(1)
PrintF("Iteration count: %U%E",ITERS)
PrintF("Clock precision: %U ms%E%E",prec)
actions(0)=Action1
actions(1)=Action2
actions(2)=Action3
Benchmark(actions,times,COUNT,ITERS)
 
FOR i=0 TO COUNT-1
DO
rate=ItersPerSecond(times(i),iters)
PrintF("Action%B: %U ms, %U times per sec%E",i+1,times(i),rate)
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Rate_counter.png Screenshot from Atari 8-bit computer]
<pre>
Iteration count: 10000
Clock precision: 50 ms
 
Action1: 1400 ms, 7143 times per sec
Action2: 2000 ms, 5000 times per sec
Action3: 47800 ms, 209 times per sec
</pre>
 
=={{header|Ada}}==
Line 16 ⟶ 133:
to get CPU times would use the package Ada.Execution_Time (Ada05).<br>
The precision of measure is given by the value of System.Tick; on Windows value is 10 ms.
<langsyntaxhighlight Adalang="ada">with System; use System;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Calendar; use Ada.Calendar;
Line 86 ⟶ 203:
end loop;
 
end Rate_Counter;</langsyntaxhighlight>
 
Output on a Linux 64 bits system:
Line 98 ⟶ 215:
0.000001 seconds is the precision of System clock.
</pre>
 
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">cube: function [z]->
z * z * z
 
loop 1..10 'x [
benchmark ->
loop 1..400 'o -> cube 5
]</syntaxhighlight>
 
{{out}}
 
<pre>[benchmark] time: 0.231ms
[benchmark] time: 0.231ms
[benchmark] time: 0.213ms
[benchmark] time: 0.184ms
[benchmark] time: 0.141ms
[benchmark] time: 0.175ms
[benchmark] time: 0.169ms
[benchmark] time: 0.254ms
[benchmark] time: 0.174ms
[benchmark] time: 0.174ms</pre>
 
=={{header|AutoHotkey}}==
===Built in variable===
The built in variable [http://ahkscript.org/docs/Variables.htm#TickCount A_TickCount] contains the number of milliseconds since the computer was rebooted. Storing this variable and later comparing it to the current value will measure the time elapsed. A_TickCount has a precision of approximately 10ms.
<langsyntaxhighlight AutoHotkeylang="autohotkey">SetBatchLines, -1
Tick := A_TickCount ; store tickcount
Loop, 1000000 {
Line 116 ⟶ 255:
t := b, b := Mod(a, b), a := t
return, a
}</langsyntaxhighlight>
'''Output:'''
<pre>4.250000 Seconds elapsed.
Line 123 ⟶ 262:
===Query Performance Counter===
The [http://www.autohotkey.com/board/topic/48063-qpx-delay-based-on-queryperformancecounter/ QPX function] by SKAN wraps the [http://msdn.microsoft.com/en-us/library/windows/desktop/ms644904%28v=vs.85%29.aspx QueryPerformanceCounter] DLL, and is precise to one thousandth of a millisecond.
<langsyntaxhighlight AutoHotkeylang="autohotkey">SetBatchLines, -1
QPX(1) ; start timer
Loop, 1000000 {
Line 145 ⟶ 284:
t := b, b := Mod(a, b), a := t
return, a
}</langsyntaxhighlight>
'''Output:'''
<pre>4.428430 Seconds elapsed.
Line 153 ⟶ 292:
The TIMER builtin returns the elapsed time since start of program run, in milliseconds.
 
<langsyntaxhighlight lang="freebasic">' Rate counter
FOR i = 1 TO 3
GOSUB timeit
Line 170 ⟶ 309:
WEND
PRINT iter, " iterations in ", i, " millisecond", IIF$(i > 1, "s", "")
RETURN</langsyntaxhighlight>
 
{{out}}
Line 178 ⟶ 317:
23977 iterations in 3 milliseconds
28167202 iterations in 2000 milliseconds</pre>
 
 
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
global i
subroutine timeit()
iter = 0
starter = msec
while True
iter += 1
if msec >= starter + i then exit while
end while
print iter; " iteraciones en "; i; " milisegundo";
if i > 1 then print "s" else print
end subroutine
 
for i = 1 to 3
call timeit()
next i
 
i = 200
call timeit()
end
</syntaxhighlight>
{{out}}
<pre>
660 iteraciones en 1 milisegundo
932 iteraciones en 2 milisegundos
1929 iteraciones en 3 milisegundos
173762 iteraciones en 200 milisegundos
</pre>
 
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> PRINT "Method 1: Calculate reciprocal of elapsed time:"
FOR trial% = 1 TO 3
start% = TIME
Line 206 ⟶ 378:
FOR i% = 1 TO 1000000
NEXT
ENDPROC</langsyntaxhighlight>
'''Sample output:'''
<pre>
Line 223 ⟶ 395:
This code stores all of the data of the rate counter and its configuration in an instance of a struct named '''rate_state_s''', and a function named '''tic_rate''' is called on that struct instance every time we complete a job. If a configured time has elapsed, '''tic_rate''' calculates and reports the tic rate, and resets the counter.
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <time.h>
 
Line 296 ⟶ 468:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
This code defines the counter as a class, '''CRateState'''. The counter's period is configured as an argument to its constructor, and the rest of the counter state is kept as class members. A member function '''Tick()''' manages updating the counter state, and reports the tic rate if the configured period has elapsed.
 
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <ctime>
 
Line 378 ⟶ 550:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|Chipmunk Basic}}==
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="vbnet">100 cls
110 for i = 1 to 3
120 gosub 170
130 next i
140 i = 200
150 gosub 170
160 end
170 'function timeit
180 iter = 0
190 starter = timer
200 while true
210 iter = iter+1
220 if timer >= starter+i then exit while
230 wend
240 print iter;" iteraciones en ";i;" milisegundo";
250 if i > 1 then print "s" else print ""
260 return</syntaxhighlight>
 
=={{header|Common Lisp}}==
Common Lisp already has a <code>time</code> macro.
<langsyntaxhighlight lang="lisp">(time (do some stuff))</langsyntaxhighlight> will give a timing report about "stuff" on the trace output. We can define something similar with repeats:
<langsyntaxhighlight lang="lisp">(defmacro time-this (cnt &rest body)
(let ((real-t (gensym)) (run-t (gensym)))
`(let (,real-t ,run-t)
Line 392 ⟶ 584:
(coerce internal-time-units-per-second 'float))
(/ (- (get-internal-run-time) ,run-t)
(coerce internal-time-units-per-second 'float))))))</langsyntaxhighlight>
 
Call the <code>time-this</code> macro to excute a loop 99 times:
<langsyntaxhighlight lang="lisp">(print (time-this 99 (loop for i below 10000 sum i)))</langsyntaxhighlight>which gives a pair of numbers, the real time and the run time, both in seconds:<syntaxhighlight lang="text">(0.023 0.022)</langsyntaxhighlight>
 
=={{header|Crystal}}==
{{trans|Ruby}}
Testing lookup speed in array versus hash:
<langsyntaxhighlight lang="ruby">require "benchmark"
 
struct Document
Line 426 ⟶ 618:
x.report("array"){searchlist.each{ |el| documents_a.any?{ |d| d == el }} }
x.report("hash") {searchlist.each{ |el| documents_h.has_key?(el) } }
end</langsyntaxhighlight>
 
System: I7-6700HQ, 3.5 GHz, Linux Kernel 5.6.17, Crystal 0.35
Line 442 ⟶ 634:
=={{header|D}}==
 
<syntaxhighlight lang="d">
<lang d>
import std.stdio;
import std.conv;
Line 464 ⟶ 656:
}
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 475 ⟶ 667:
 
</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Diagnostics}}
{{Trans|D}}
<syntaxhighlight lang="delphi">
program Rate_counter;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
System.Diagnostics;
 
var
a: Integer;
 
function TickToString(Tick: Int64): string;
var
ns, us, ms, s, t: Cardinal;
begin
Result := '';
ns := (Tick mod 10) * 100;
if ns > 0 then
Result := format(' %dns', [ns]);
 
t := Tick div 10;
us := t mod 1000;
if us > 0 then
Result := format(' %dus', [us]) + Result;
 
t := t div 1000;
ms := t mod 1000;
if ms > 0 then
Result := format(' %dms', [ms]) + Result;
 
t := t div 1000;
s := t mod 1000;
if s > 0 then
Result := format(' %ds', [s]) + Result;
end;
 
function Benchmark(Fns: TArray<TProc>; times: Cardinal): TArray<string>;
var
Stopwatch: TStopwatch;
fn: TProc;
i, j: Cardinal;
begin
SetLength(result, length(Fns));
Stopwatch := TStopwatch.Create;
 
for i := 0 to High(Fns) do
begin
fn := Fns[i];
if not Assigned(fn) then
Continue;
Stopwatch.Reset;
Stopwatch.Start;
for j := 1 to times do
fn();
Stopwatch.Stop;
Result[i] := TickToString(Stopwatch.ElapsedTicks);
end;
end;
 
procedure F0();
begin
end;
 
procedure F1();
begin
var b := a;
end;
 
procedure F2();
begin
var b := a.ToString;
end;
 
begin
writeln('Time fx took to run 10,000 times:'#10);
var r := Benchmark([F0, F1, F2], 10000);
for var i := 0 to High(r) do
writeln('f', i, ': ', r[i]);
Readln;
end.</syntaxhighlight>
{{out}}
<pre>Time fx took to run 10,000 times:
 
f0: 32us 400ns
f1: 34us 600ns
f2: 607us 100ns</pre>
 
=={{header|E}}==
<langsyntaxhighlight lang="e">def makeLamportSlot := <import:org.erights.e.elib.slot.makeLamportSlot>
 
The rate counter:
Line 500 ⟶ 783:
return [signal, &rate]
}</langsyntaxhighlight>
 
The test code:
 
<langsyntaxhighlight lang="e">/** Dummy task: Retrieve http://localhost/ and return the content. */
def theJob() {
return when (def text := <http://localhost/> <- getText()) -> {
Line 537 ⟶ 820:
signal()
theJob()
})</langsyntaxhighlight>
 
=={{header|EasyLang}}==
[https://easylang.dev/show/#cod=RYzLCsIwEEX3+YpDF+IDyygUV+m/hDZCIA9JB8G/l4SKm8sc5ty7lFgqDxFTMi6H5NQbYIne1XZUt3KxyHhvlMrbMwmTdCnUJfqmNArPLs/7c+9aOo0tFMv22TQkvxdUmPnprxqychMRzhyVKyonDgykbfiPCBY1Pq/mCw== Run it]
<syntaxhighlight>
color 700
on animate
clear
rad += 0.2
move 50 50
circle rad
if rad > 50
rad = 0
.
t = systime
if t0 > 0
print 1000 * (t - t0) & " ms"
.
t0 = t
end
</syntaxhighlight>
{{out}}
<pre>
17.00 ms
17.00 ms
16.00 ms
.
.
</pre>
 
=={{header|Erlang}}==
Measuring elapsed time is built into the timer module. Doing something during a time period requires code. For normal use the Fun should take a large amount of microseconds, our unit of measurement.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( rate_counter ).
 
Line 575 ⟶ 886:
end.
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 587 ⟶ 898:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM RATE_COUNTER
 
Line 623 ⟶ 934:
END FOR
END PROGRAM
</syntaxhighlight>
</lang>
Time elapsed is measured with TIMER function (taken from computer clock).
{{out}}
Line 642 ⟶ 953:
Similarly, an installation may offer local routines to report the date and time, and F90 has introduced an intrinsic that can be invoked as <code>CALL DATE_AND_TIME(VALUES = MARK)</code> where MARK is an eight-element integer array, rather exhaustingly returning year, month, day, minutes from GMT (or UT, ''etc''), hour, minute, second, milliseconds.
 
So, in <langsyntaxhighlight Fortranlang="fortran"> DO I = FIRST,LAST
IF (PROGRESSNOTE((I - FIRST)/(LAST - FIRST + 1.0))) WRITE (6,*) "Reached ",I,", towards ",LAST
...much computation...
END DO</langsyntaxhighlight>
Function PROGRESSNOTE is invoked at the start of each iteration, with its parameter stating how much progress has been made on a scale of zero to one, with a "zero progress" restarting its timers. The function notes whether sufficient clock time has elapsed since its previous report (more than six seconds, for example) and if so, returns ''true'' after starting an output line with a standard report giving an estimated time to run and an estimated time (and date, if not the current day) of finishing. This line is not terminated; the invoking routine appends its own progress message, tailored to the nature of the task it is working through. For instance,
<pre>
Line 659 ⟶ 970:
 
For another approach, imagine a long-running program, WORKER, that writes various remarks to standard output as it goes, and consider another, TIMESTAMP, that copies from standard input to standard output, prefixing each line with a date and time stamp, perhaps invoked via something like <code>WORKER | TIMESTAMP >Log.txt</code> - the vertical bar an amusing choice to symbolise a horizontal "pipe". When everything finishes, the log file can be analysed to determine the rate of progress. But alas, in the windows world, the stages of a "pipeline" are performed serially, not simultaneously - the vertical bar symbolising this separation. All output from WORKER will be saved in a temporary disc file then when WORKER finishes that file will be fed as input to TIMESTAMP, thereby producing data only on the rate of file input/output.
 
 
=={{header|FreeBASIC}}==
{{trans|BaCon}}
<syntaxhighlight lang="freebasic">
Dim Shared As Integer i
 
Sub timeit
Dim As Integer iter = 0
Dim As Double starter = Timer
While True
iter += 1
If Timer >= starter + i Then Exit While
Wend
Print iter; " iteraciones en"; i; " milisegundo"; Iif(i > 1, "s", "")
End Sub
 
For i = 1 To 3
timeit
Next i
 
i = 200 : timeit
Sleep
</syntaxhighlight>
{{out}}
<pre>
44804265 iteraciones en 1 milisegundo
91122566 iteraciones en 2 milisegundos
137725199 iteraciones en 3 milisegundos
8426682089 iteraciones en 200 milisegundos
</pre>
 
 
=={{header|Go}}==
{{trans|C}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 713 ⟶ 1,056:
latest = time.Now()
}
}</langsyntaxhighlight>
Output:
<pre>
Line 723 ⟶ 1,066:
=={{header|Haskell}}==
This solution returns the time deltas in picosecond resolution.
<langsyntaxhighlight lang="haskell">
import Control.Monad
import Control.Concurrent
Line 746 ⟶ 1,089:
 
main = timeit 10 (threadDelay 1000000)
</syntaxhighlight>
</lang>
 
=={{header|HicEst}}==
The script opens a modeless dialog with 3 buttons: "Hits++" to increase Hits, "Count 5 sec" to reset Hits and initialize a delayed call to F5 after 5 sec, "Rate" to display the current rate on the status bar.
<langsyntaxhighlight HicEstlang="hicest">CHARACTER prompt='Count "Hits++" for 5 sec, get current rate'
 
DLG(Button="1:&Hits++", CALL="cb", B="2:&Count 5sec", B="3:&Rate", RC=retcod, TItle=prompt, WIN=hdl)
Line 769 ⟶ 1,112:
SUBROUTINE F5 ! called 5 sec after button "5 sec"
WRITE(StatusBar) Hits, "hits last 5 sec"
END</langsyntaxhighlight>
 
=={{header|J}}==
'''Solution'''<br>
<langsyntaxhighlight lang="j"> x (6!:2) y</langsyntaxhighlight>
The foreign conjunction <code>6!:2</code> will execute the code <code>y</code> (right argument), <code>x</code> times (left argument) and report the average time in seconds required for one execution.
 
'''Example:'''
<langsyntaxhighlight lang="j"> list=: 1e6 ?@$ 100 NB. 1 million random integers from 0 to 99
freqtable=: ~. ,. #/.~ NB. verb to calculate and build frequency table
20 (6!:2) 'freqtable list' NB. calculate and build frequency table for list, 20 times
0.00994106</langsyntaxhighlight>
 
Note, if instead we want distinct times instead of averaged times we can use a repeated counter for the number of times to execute the code
 
<langsyntaxhighlight lang="j"> 1 1 1 (6!:2) 'freqtable list'
0.0509995 0.0116702 0.0116266</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|JavaScript}}
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.util.function.Consumer;
 
public class RateCounter {
Line 808 ⟶ 1,151:
return timings;
}
}</langsyntaxhighlight>
 
<pre>70469.0
Line 824 ⟶ 1,167:
{{trans|JavaScript}}
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.util.function.IntConsumer;
import java.util.stream.DoubleStream;
 
Line 856 ⟶ 1,199:
;
}
}</langsyntaxhighlight>
 
<pre>81431.0
Line 872 ⟶ 1,215:
The ''benchmark'' function below executes a given function n times, calling it with the specified arguments. After execution of all functions, it returns an array with the execution time of each execution, in milliseconds.
 
<langsyntaxhighlight lang="javascript">function millis() { // Gets current time in milliseconds.
return (new Date()).getTime();
}
Line 885 ⟶ 1,228:
}
return times;
}</langsyntaxhighlight>
 
=={{header|jq}}==
'''Works with jq and gojq, that is, the C and Go implementations of jq.'''
 
In this entry, the times to compute `x*x*x` are compared with the times to compute `pow(x;3)`.
 
Note that jq only has direct access to the system clock ("now").
<syntaxhighlight lang=jq>
def cube: . * . * .;
 
def pow3: pow(.; 3);
 
def benchmark($n; func; $arg; $calls):
reduce range(0; $n) as $i ([];
now as $_
| (range(0; $calls) | ($arg | func)) as $x
# milliseconds:
| . + [(now - $_) * 1000 | floor] ) ;
 
"Timings (total elapsed time in milliseconds):",
"cube pow3",
([benchmark(10; cube; 5; 1e5), benchmark(10; pow3; 5; 1e5)]
| transpose[]
| "\(.[0]) \(.[1])" )
</syntaxhighlight>
'''Invocation''': jq -nr -f rate-counter.jq
{{{output}}
<pre>
Timings (total elapsed time in milliseconds):
cube pow3
205 178
164 182
182 156
173 173
167 154
181 175
180 176
176 160
186 206
173 174
</pre>
 
 
=={{header|Jsish}}==
<langsyntaxhighlight lang="javascript">#!/usr/bin/env jsish
"use strict";
/* Rate counter, timer access, in Jsish */
Line 907 ⟶ 1,292:
timer = times(sleeper, 100);
puts(timer, 'μs to sleep 10 ms, 100 times');
}</langsyntaxhighlight>
 
{{out}}
Line 919 ⟶ 1,304:
=={{header|Julia}}==
The elapsed() macro in Julia generally is accurate in the nanosecond range.
<langsyntaxhighlight lang="julia">dosomething() = sleep(abs(randn()))
 
function runNsecondsworthofjobs(N)
Line 940 ⟶ 1,325:
 
runNsecondsworthofjobs(5)
</langsyntaxhighlight>{{output}}<pre> Ran job 5 times, for total time of 5.215301074 seconds.
Average time per run was 1.0430602148 seconds.
Individual times of the jobs in seconds were:
Line 952 ⟶ 1,337:
=={{header|Kotlin}}==
{{trans|JavaScript}}
<langsyntaxhighlight lang="scala">// version 1.1.3
 
typealias Func<T> = (T) -> T
Line 971 ⟶ 1,356:
println("\nTimings (nanoseconds) : ")
for (time in benchmark(10, ::cube, 5)) println(time)
}</langsyntaxhighlight>
 
Sample output:
Line 989 ⟶ 1,374:
=={{header|Liberty BASIC}}==
precision depends on OS. It is 16 (sometines cames as 15) ms for XP and 10 ms for Win2000.
<syntaxhighlight lang="lb">
<lang lb>
Print "Rate counter"
print "Precision: system clock, ms ";
Line 1,046 ⟶ 1,431:
testFunc = s
end function
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
The first parameter for both of these functions can be any program code.
<syntaxhighlight lang="text">jobRateCounted[fn_,Y_Integer]:=First[AbsoluteTiming[Do[fn,{Y}]]/Y;
 
<lang>jobRateCounted[fn_,Y_Integer]:=First[AbsoluteTiming[Do[fn,{Y}]]/Y;
SetAttributes[jobRateCounted,HoldFirst]
 
jobRatePeriod[fn_,time_]:=Block[{n=0},TimeConstrained[While[True,fn;n++]];n/time];
SetAttributes[jobRatePeriod,HoldFirst]</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Kotlin}}
<syntaxhighlight lang="nim">import sugar, std/monotimes, times
 
type Func[T] = (T) -> T
 
func cube(n: int): int = n * n * n
 
proc benchmark[T](n: int; f: Func[T]; arg: T): seq[Duration] =
result.setLen(n)
for i in 0..<n:
let m = getMonoTime()
discard f(arg)
result[i] = getMonoTime() - m
 
echo "Timings (nanoseconds):"
for time in benchmark(10, cube, 5):
echo time.inNanoseconds</syntaxhighlight>
 
{{out}}
<pre>Timings (nanoseconds):
556
170
88
93
91
93
109
96
91
92</pre>
 
=={{header|OxygenBasic}}==
Rate Counter Deluxe, giving start and finish times + duration. The duration is measured in seconds using the system performance counter, resolved to the nearest microsecond.
<langsyntaxhighlight lang="oxygenbasic">
'========
'TIME API
Line 1,178 ⟶ 1,593:
'Finish: 2012-07-01 00:52:36:974
'Sunday July 01 2012
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">a=0;
b=0;
for(n=1,20000000,
Line 1,190 ⟶ 1,605:
a=a+gettime();
if(a>60000,print(b);a=0;b=0)
)</langsyntaxhighlight>
 
=={{header|Perl}}==
The [http://perldoc.perl.org/Benchmark.html Benchmark] module can rate code per time, or per loops executed:
<langsyntaxhighlight lang="perl">use Benchmark;
 
timethese COUNT,{ 'Job1' => &job1, 'Job2' => &job2 };
Line 1,205 ⟶ 1,620:
{
...job2 code...
}</langsyntaxhighlight>
A negative COUNT will run each job for at least COUNT seconds.<br>
A positive COUNT will run each job COUNT times.
Line 1,211 ⟶ 1,626:
=={{header|Phix}}==
On windows, time() advances in ~0.015s increments, whereas on linux it is ~0.0000016s.
<!--<syntaxhighlight lang="phix">-->
<lang Phix>procedure task_to_measure()
<span style="color: #008080;">procedure</span> <span style="color: #000000;">task_to_measure</span><span style="color: #0000FF;">()</span>
sleep(0.1)
<span style="color: #7060A8;">sleep</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0.1</span><span style="color: #0000FF;">)</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
printf(1,"method 1: calculate reciprocal of elapsed time:\n")
<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;">"method 1: calculate reciprocal of elapsed time:\n"</span><span style="color: #0000FF;">)</span>
for trial=1 to 3 do
<span style="color: #008080;">for</span> <span style="color: #000000;">trial</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">3</span> <span style="color: #008080;">do</span>
atom t=time()
<span style="color: #004080;">atom</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
task_to_measure()
<span style="color: #000000;">task_to_measure</span><span style="color: #0000FF;">()</span>
t = time()-t
<span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t</span>
string r = iff(t?sprintf("%g",1/t):"inf")
<span style="color: #004080;">string</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">?</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%g"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">/</span><span style="color: #000000;">t</span><span style="color: #0000FF;">):</span><span style="color: #008000;">"inf"</span><span style="color: #0000FF;">)</span>
printf(1,"rate = %s per second\n",{r})
<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;">"rate = %s per second\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">r</span><span style="color: #0000FF;">})</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,"method 2: count completed tasks in one second:\n")
<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;">"method 2: count completed tasks in one second:\n"</span><span style="color: #0000FF;">)</span>
for trial=1 to 3 do
<span style="color: #008080;">for</span> <span style="color: #000000;">trial</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">3</span> <span style="color: #008080;">do</span>
integer runs=0
<span style="color: #004080;">integer</span> <span style="color: #000000;">runs</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span>
atom finish=time()+1
<span style="color: #004080;">atom</span> <span style="color: #000000;">finish</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()+</span><span style="color: #000000;">1</span>
while true do
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
task_to_measure()
<span style="color: #000000;">task_to_measure</span><span style="color: #0000FF;">()</span>
if time()>=finish then exit end if
<span style="color: #008080;">if</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()>=</span><span style="color: #000000;">finish</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
runs += 1
<span style="color: #000000;">runs</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
printf(1,"rate = %d per second\n",runs)
<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;">"rate = %d per second\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">runs</span><span style="color: #0000FF;">)</span>
end for</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
Of course it fails to achieve the perfect 10/s, due to the overhead of call/ret/time/printf etc.
Line 1,249 ⟶ 1,666:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">100000 var iterations
2 4 2 tolist
for
Line 1,260 ⟶ 1,677:
"take " print dif print " secs" print
" or " print iterations dif / print " sums per second" print nl
endfor</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
Line 1,266 ⟶ 1,683:
microseconds. This can be used, for example, to measure the time between two key
strokes
<langsyntaxhighlight PicoLisplang="picolisp">(prin "Hit a key ... ")
(key)
(prinl)
Line 1,273 ⟶ 1,690:
(key)
(prinl)
(prinl "This took " (format (- (usec) Usec) 6) " seconds") )</langsyntaxhighlight>
Output:
<pre>Hit a key ...
Line 1,280 ⟶ 1,697:
The [http://software-lab.de/doc/refB.html#bench bench] benchmark function could
also be used. Here we measure the time until a key is pressed
<syntaxhighlight lang PicoLisp="picolisp">(bench (key))</langsyntaxhighlight>
<pre>1.761 sec
-> "a"</pre>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
[datetime]$start = Get-Date
 
Line 1,306 ⟶ 1,723:
 
$rate | Format-List
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,318 ⟶ 1,735:
=={{header|PureBasic}}==
===Counting frequence of an event===
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.d TimesPSec(Reset=#False)
Static starttime, cnt
Protected Result.d, dt
Line 1,352 ⟶ 1,769:
EndIf
Until Event=#PB_Event_CloseWindow
EndIf</langsyntaxhighlight>
 
===Counting events for a time period===
<langsyntaxhighlight PureBasiclang="purebasic">Procedure DummyThread(arg)
Define.d dummy=#PI*Pow(arg,2)/4
EndProcedure
Line 1,367 ⟶ 1,784:
 
msg$="We got "+Str(cnt)+" st."+Chr(10)+StrF(cnt/10,2)+" threads per sec."
MessageRequester("Counting threads in 10 sec",msg$)</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">import subprocess
import time
 
Line 1,427 ⟶ 1,844:
taskTimer( int(sys.argv[1]), sys.argv[2:])
 
main()</langsyntaxhighlight>
Usage Example:
First argument is the number of times to iterate. Additional arguments are command to execute.
Line 1,433 ⟶ 1,850:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 1,446 ⟶ 1,863:
;; But of course, can be used to measure external processes too:
(time* 10 (system "sleep 1"))
</syntaxhighlight>
</lang>
 
Sample output:
Line 1,480 ⟶ 1,897:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub runrate($N where $N > 0, &todo) {
my $n = $N;
 
Line 1,497 ⟶ 1,914:
sub factorial($n) { (state @)[$n] //= $n < 2 ?? 1 !! $n * factorial($n-1) }
 
runrate 10000100_000, { state $n = 1; factorial($n++) }
 
runrate 10000100_000, { state $n = 1; factorial($n++) }</langsyntaxhighlight>
{{out}}
<pre>Start time: 20132023-0304-08T2019T08:5723:02Z50.276418Z
End time: 20132023-0304-08T2019T08:5723:03Z54.716864Z
Elapsed time: 14.5467497440445313 seconds
Rate: 646522520.1726 per second
 
Start time: 20132023-0304-08T2019T08:5723:03Z54.726913Z
End time: 20132023-0304-08T2019T08:5723:04Z54.798238Z
Elapsed time: 0.7036318071324057 seconds
Rate: 142111402051.9848 per second</pre>
</pre>
The <tt>Instant</tt> type in Perl 6 is defined to be based on TAI seconds, and represented with rational numbers that are more than sufficiently accurate to represent your clock's accuracy. The actual accuracy will depend on your clock's accuracy (even if you don't have an atomic clock in your kitchen, your smartphone can track various orbiting atomic clocks, right?) modulo the vagaries of returning the atomic time (or unreasonable facsimile) via system calls and library APIs.
 
Line 1,515 ⟶ 1,933:
Programming note: &nbsp; The &nbsp; '''$CALC''' &nbsp; (REXX) program which is invoked below is a general purpose calculator which supports a multitude
<br>of functions (over 1,500), &nbsp; and can show the results in many different formats &nbsp; (some of which are shown here).
<langsyntaxhighlight lang="rexx">/*REXX program reports on the amount of elapsed time 4 different tasks use (wall clock).*/
time.= /*nullify times for all the tasks below*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
Line 1,549 ⟶ 1,967:
say 'time used for task' j "was" right(format(time.j,,0),4) 'seconds.'
end /*j*/
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output''' &nbsp; (of the tasks as well as the above REXX timer program):
 
Line 1,721 ⟶ 2,139:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Rate counter
 
Line 1,748 ⟶ 2,166:
for i = 1 to 100000
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,763 ⟶ 2,181:
=={{header|Ruby}}==
Testing lookup speed in array versus hash:
<langsyntaxhighlight lang="ruby">require 'benchmark'
Document = Struct.new(:id,:a,:b,:c)
documents_a = []
Line 1,777 ⟶ 2,195:
x.report('array'){searchlist.each{|el| documents_a.any?{|d| d.id == el}} }
x.report('hash'){searchlist.each{|el| documents_h.has_key?(el)} }
end</langsyntaxhighlight>
 
System: I7-6700HQ, 3.5 GHz, Linux Kernel 5.6.17, Ruby 2.7.1
Line 1,791 ⟶ 2,209:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">html "<table bgcolor=wheat border=1><tr><td align=center colspan=2>Rate Counter</td></tr>
<tr><td>Run Job Times</td><td>"
textbox #runTimes,"10",3
Line 1,835 ⟶ 2,253:
cpsi = cosi + cos(i)
next
end function </langsyntaxhighlight>
Output:
 
Line 1,862 ⟶ 2,280:
once the time is up.
 
<langsyntaxhighlight lang="scala">def task(n: Int) = Thread.sleep(n * 1000)
def rate(fs: List[() => Unit]) = {
val jobs = fs map (f => scala.actors.Futures.future(f()))
Line 1,873 ⟶ 2,291:
}
rate(List.fill(30)(() => task(scala.util.Random.nextInt(10)+1)))
</syntaxhighlight>
</lang>
 
The solution below runs a task repeatedly, for at most N seconds or Y times. The
Line 1,880 ⟶ 2,298:
result, if the time runs out.
 
<langsyntaxhighlight lang="scala">def rate(n: Int, y: Int)(task: => Unit) {
val startTime = System.currentTimeMillis
var currTime = startTime
Line 1,894 ⟶ 2,312:
println("Rate %d times in %.3f seconds" format (y, (currTime - startTime).toDouble / 1000))
}
rate(5, 20)(task(2))</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">var benchmark = frequire('Benchmark');
 
func job1 {
Line 1,908 ⟶ 2,326:
 
const COUNT = -1; # run for one CPU second
benchmark.timethese(COUNT, Hash.new('Job1' => job1, 'Job2' => job2));</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|Pharo}}
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">|times|
times := Bag new.
1 to: 10 do: [:n| times add:
(Time millisecondsToRun: [3000 factorial])].
Transcript show: times average asInteger.</langsyntaxhighlight>
Output:
<pre>153</pre>
Line 1,923 ⟶ 2,341:
=={{header|Tcl}}==
The standard Tcl mechanism to measure how long a piece of code takes to execute is the <code>time</code> command. The first word of the string returned (which is also always a well-formed list) is the number of microseconds taken (in absolute time, not CPU time). Tcl uses the highest performance calibrated time source available on the system to compute the time taken; on Windows, this is derived from the system performance counter and not the (poor quality) standard system time source.
<langsyntaxhighlight lang="tcl">set iters 10
 
# A silly example task
Line 1,938 ⟶ 2,356:
}] 0]
puts "task took $t microseconds on iteration $i"
}</langsyntaxhighlight>
When tasks are are very quick, a more accurate estimate of the time taken can be gained by repeating the task many times between time measurements. In this next example, the task (a simple assignment) is repeated a million times between measures (this is very useful when performing performance analysis of the Tcl implementation itself).
<langsyntaxhighlight lang="tcl">puts [time { set aVar 123 } 1000000]</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 1,948 ⟶ 2,366:
<br>
This script spins, executing '''task''' as many times as possible.
<langsyntaxhighlight lang="bash">#!/bin/bash
 
while : ; do
task && echo >> .fc
done</langsyntaxhighlight>
 
Part 2:
<br>
This script runs '''foo.sh''' in the background, and checks the rate count file every five seconds. After four such checks, twenty seconds will have elapsed.
<langsyntaxhighlight lang="bash">./foo.sh &
sleep 5
mv .fc .fc2 2>/dev/null
Line 1,971 ⟶ 2,389:
killall foo.sh
wc -l .fc 2>/dev/null
rm .fc</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">import rand
import time
 
// representation of time.Time is nanosecond, actual resolution system specific
struct RateStateS {
mut:
last_flush time.Time
period time.Duration
tick_count int
}
fn (mut p_rate RateStateS) tic_rate() {
p_rate.tick_count++
now := time.now()
if now-p_rate.last_flush >= p_rate.period {
// TPS Report
mut tps := 0.0
if p_rate.tick_count > 0 {
tps = f64(p_rate.tick_count) / (now-p_rate.last_flush).seconds()
}
println("$tps tics per second.")
// Reset
p_rate.tick_count = 0
p_rate.last_flush = now
}
}
fn something_we_do() {
time.sleep(time.Duration(i64(9e7) + rand.i64n(i64(2e7)) or {i64(0)})) // sleep about .1 second.
}
fn main() {
start := time.now()
mut rate_watch := RateStateS{
last_flush: start,
period: 5 * time.second,
}
// Loop for twenty seconds
mut latest := start
for latest-start < 20*time.second {
something_we_do()
rate_watch.tic_rate()
latest = time.now()
}
}</syntaxhighlight>
Output:
<pre>
10.029074483576407 tics per second.
9.946060524563189 tics per second.
9.97480364599023 tics per second.
</pre>
 
=={{header|Wren}}==
Line 1,980 ⟶ 2,455:
 
Note that, in an attempt to obtain more meaningful times, I've called the function 1 million times compared to just one in the Kotlin example which uses a more accurate timer.
<langsyntaxhighlight ecmascriptlang="wren">var cube = Fn.new { |n| n * n * n }
 
var benchmark = Fn.new { |n, func, arg, calls|
Line 1,993 ⟶ 2,468:
 
System.print("Timings (milliseconds) : ")
for (time in benchmark.call(10, cube, 5, 1e6)) System.print(time)</langsyntaxhighlight>
 
{{out}}
Line 2,012 ⟶ 2,487:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int N, I, T0, Time;
[for N:= 1, 3 do
Line 2,024 ⟶ 2,499:
RlOut(0, 100.0e6/float(Time)); Text(0, "Hz"); CrLf(0);
];
]</langsyntaxhighlight>
 
Example output of vertical blanking (screen refresh) rates:
Line 2,052 ⟶ 2,527:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">iterations = 100000
 
for j = 2 to 4
Line 2,062 ⟶ 2,537:
print "take ", dif, " ms";
print " or ", iterations / dif * 1000 using "########", " sums per second"
next</langsyntaxhighlight>
 
=={{header|zkl}}==
One second resolution and we let the computation run to completion. We could run the computation in a thread and signal it if time is up but that doesn't seem reasonable.
<langsyntaxhighlight lang="zkl">fcn rateCounter(f,timeNRuns,secsToRun=Void){
now:=Time.Clock.time;
if(secsToRun){
Line 2,083 ⟶ 2,558:
t
}
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">ns:=List.createLong(0d100_000,(0).random,True); // one hundred thousand ints
rateCounter('wrap(){ ns.copy().sort() },20);
rateCounter('wrap(){ ns.copy().sort() },Void,10);</langsyntaxhighlight>
{{out}}
<pre>
2,122

edits