Rate counter: Difference between revisions

Added Chipmunk Basic
(→‎{{header|XPL0}}: added zkl)
(Added Chipmunk Basic)
 
(47 intermediate revisions by 22 users not shown)
Line 12:
'''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 17 ⟶ 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 87 ⟶ 203:
end loop;
 
end Rate_Counter;</langsyntaxhighlight>
 
Output on a Linux 64 bits system:
Line 99 ⟶ 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 117 ⟶ 255:
t := b, b := Mod(a, b), a := t
return, a
}</langsyntaxhighlight>
'''Output:'''
<pre>4.250000 Seconds elapsed.
Line 124 ⟶ 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 146 ⟶ 284:
t := b, b := Mod(a, b), a := t
return, a
}</langsyntaxhighlight>
'''Output:'''
<pre>4.428430 Seconds elapsed.
225814 Loop iterations per second.</pre>
 
=={{header|BaCon}}==
The TIMER builtin returns the elapsed time since start of program run, in milliseconds.
 
<syntaxhighlight lang="freebasic">' Rate counter
FOR i = 1 TO 3
GOSUB timeit
NEXT
 
i = 2000
GOSUB timeit
END
 
LABEL timeit
iter = 0
starter = TIMER
WHILE TRUE DO
INCR iter
IF TIMER >= starter + i THEN BREAK
WEND
PRINT iter, " iterations in ", i, " millisecond", IIF$(i > 1, "s", "")
RETURN</syntaxhighlight>
 
{{out}}
<pre>prompt$ ./rate-counter
6169 iterations in 1 millisecond
16025 iterations in 2 milliseconds
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 178 ⟶ 378:
FOR i% = 1 TO 1000000
NEXT
ENDPROC</langsyntaxhighlight>
'''Sample output:'''
<pre>
Line 195 ⟶ 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 268 ⟶ 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 350 ⟶ 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 364 ⟶ 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:
<syntaxhighlight lang="ruby">require "benchmark"
 
struct Document
property :id
def initialize(@id : Int32) end
end
 
documents_a = [] of Int32 | Document
documents_h = {} of Int32 => Int32 | Document
 
1.upto(10_000) do |n|
d = Document.new(n)
documents_a << d
documents_h[d.id] = d
end
 
searchlist = Array.new(1000){ rand(10_000)+1 }
Benchmark.bm do |x|
x.report("array"){searchlist.each{ |el| documents_a.any?{ |d| d == el }} }
x.report("hash") {searchlist.each{ |el| documents_h.has_key?(el) } }
end
puts
Benchmark.ips do |x|
x.report("array"){searchlist.each{ |el| documents_a.any?{ |d| d == el }} }
x.report("hash") {searchlist.each{ |el| documents_h.has_key?(el) } }
end</syntaxhighlight>
 
System: I7-6700HQ, 3.5 GHz, Linux Kernel 5.6.17, Crystal 0.35
Run as: $ crystal run ratecounter.cr --release
 
{{out}}
<pre> user system total real
array 0.006493 0.000736 0.007229 ( 0.007223)
hash 0.000015 0.000008 0.000023 ( 0.000023)
 
array 166.53 ( 6.00ms) (± 1.87%) 0.0B/op 545.27× slower
hash 90.81k ( 11.01µs) (± 4.16%) 0.0B/op fastest
</pre>
 
=={{header|D}}==
 
<syntaxhighlight lang="d">
import std.stdio;
import std.conv;
import std.datetime.stopwatch;
 
int a;
void f0() {}
void f1() { auto b = a; }
void f2() { auto b = to!string(a); }
 
void main()
{
auto r = benchmark!(f0, f1, f2)(10_000);
 
writeln("Time fx took to run 10,000 times:\n");
writeln("f0: ", r[0]);
writeln("f1: ", r[1]);
writeln("f2: ", r[2]);
}
 
</syntaxhighlight>
 
{{out}}
<pre>
Time fx took to run 10,000 times:
 
f0: 37 μs and 7 hnsecs
f1: 56 μs and 2 hnsecs
f2: 1 ms, 966 μs, and 6 hnsecs
 
</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 393 ⟶ 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 430 ⟶ 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 468 ⟶ 886:
end.
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 480 ⟶ 898:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM RATE_COUNTER
 
Line 516 ⟶ 934:
END FOR
END PROGRAM
</syntaxhighlight>
</lang>
Time elapsed is measured with TIMER function (taken from computer clock).
{{out}}
Line 529 ⟶ 947:
Rate = 15 per second
</pre>
 
=={{header|Fortran}}==
Standard Fortran does not offer facilities for starting another task, nor for monitoring such a task's consumption of cpu time against clock time. However, a program can monitor its ''own'' usage by invoking a suitable routine at appropriate points in its computation, say on each new iteration of its outermost DO-loop, and thus generate progress reports that could also include an estimated time of finishing. This requires access to system timers, usually achieved via invocations of special routines that are often specific to an installation. But F90 introduced the intrinsic <code>CALL CPU_TIME(T)</code> that returns a "processor-dependent approximation of the processor time in seconds" in <code>T</code> a floating-point variable.
 
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 <syntaxhighlight lang="fortran"> DO I = FIRST,LAST
IF (PROGRESSNOTE((I - FIRST)/(LAST - FIRST + 1.0))) WRITE (6,*) "Reached ",I,", towards ",LAST
...much computation...
END DO</syntaxhighlight>
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>
Standard progress report|Tailored message.
ETF + 6·2hrs!@Monday 17/ 7/2017 5:23:25·013am. 0% Dumping Monday 3/ 2/1749.
ETF + 6·2hrs!@Monday 17/ 7/2017 5:23:37·167am. 0% Dumping Sunday 9/ 3/1749.
ETF + 6·2hrs!@Monday 17/ 7/2017 5:26:06·383am. 0% Dumping Friday 11/ 4/1749.
ETF + 6·1hrs!@Monday 17/ 7/2017 5:21:23·397am. 0% Dumping Friday 16/ 5/1749.
</pre>
Thus, the human waiting at the computer screen can monitor the rate of progress and know to go for a walk, or not.
 
Incidentally, on windows systems at least, frequent invocations of the date and time routine can cause execution to run ''much'' slower, or worse. A loop waiting for the system's DATE_AND_TIME result to attain a specified value will instead cause a crash.
 
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 583 ⟶ 1,056:
latest = time.Now()
}
}</langsyntaxhighlight>
Output:
<pre>
Line 593 ⟶ 1,066:
=={{header|Haskell}}==
This solution returns the time deltas in picosecond resolution.
<langsyntaxhighlight lang="haskell">
import Control.Monad
import Control.Concurrent
Line 616 ⟶ 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 639 ⟶ 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 678 ⟶ 1,151:
return timings;
}
}</langsyntaxhighlight>
 
<pre>70469.0
Line 694 ⟶ 1,167:
{{trans|JavaScript}}
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.util.function.IntConsumer;
import java.util.stream.DoubleStream;
 
Line 726 ⟶ 1,199:
;
}
}</langsyntaxhighlight>
 
<pre>81431.0
Line 742 ⟶ 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 755 ⟶ 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}}==
<syntaxhighlight lang="javascript">#!/usr/bin/env jsish
"use strict";
/* Rate counter, timer access, in Jsish */
 
/* System time in milliseconds */
var runs = 0, newMs;
function countJobsIsTheJob() { runs += 1; }
var milliSeconds = strptime();
while ((newMs = strptime()) < (milliSeconds + 1000)) { countJobsIsTheJob(); }
puts(runs, 'runs in', newMs - milliSeconds, 'ms');
 
 
/* Builtin times test(callback, runs), result in microseconds */
function sleeper() { sleep(10); }
 
var timer;
for (var i = 1; i < 4; i++) {
timer = times(sleeper, 100);
puts(timer, 'μs to sleep 10 ms, 100 times');
}</syntaxhighlight>
 
{{out}}
<pre>
prompt$ jsish rateCounter.jsi
81494 runs in 1000 ms
1019410 μs to sleep 10 ms, 100 times
1018384 μs to sleep 10 ms, 100 times
1018984 μs to sleep 10 ms, 100 times</pre>
 
=={{header|Julia}}==
The elapsed() macro in Julia generally is accurate in the nanosecond range.
<syntaxhighlight lang="julia">dosomething() = sleep(abs(randn()))
 
function runNsecondsworthofjobs(N)
times = Vector{Float64}()
totaltime = 0
runcount = 0
while totaltime < N
t = @elapsed(dosomething())
push!(times, t)
totaltime += t
runcount += 1
end
println("Ran job $runcount times, for total time of $totaltime seconds.")
println("Average time per run was $(sum(times)/length(times)) seconds.")
println("Individual times of the jobs in seconds were:")
for t in times
println(" $t")
end
end
 
runNsecondsworthofjobs(5)
</syntaxhighlight>{{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:
1.901202753
0.706044625
0.485377196
0.489283165
1.633393335
</pre>
 
=={{header|Kotlin}}==
{{trans|JavaScript}}
<syntaxhighlight lang="scala">// version 1.1.3
 
typealias Func<T> = (T) -> T
 
fun cube(n: Int) = n * n * n
 
fun <T> benchmark(n: Int, func: Func<T>, arg: T): LongArray {
val times = LongArray(n)
for (i in 0 until n) {
val m = System.nanoTime()
func(arg)
times[i] = System.nanoTime() - m
}
return times
}
 
fun main(args: Array<String>) {
println("\nTimings (nanoseconds) : ")
for (time in benchmark(10, ::cube, 5)) println(time)
}</syntaxhighlight>
 
Sample output:
<pre>
154430
2100
1275
1138
1063
1113
1087
1088
1063
1025
</pre>
 
=={{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 816 ⟶ 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;
SetAttributes[jobRateCounted,HoldFirst]
jobRatePeriod[fn_,time_]:=Block[{n=0},TimeConstrained[While[True,fn;n++]];n/time];
SetAttributes[jobRatePeriod,HoldFirst]</syntaxhighlight>
 
=={{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 939 ⟶ 1,593:
'Finish: 2012-07-01 00:52:36:974
'Sunday July 01 2012
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}==
The first parameter for both of these functions can be any program code.
 
<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]</lang>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">a=0;
b=0;
for(n=1,20000000,
Line 960 ⟶ 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 975 ⟶ 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.
=={{header|Perl 6}}==
<lang perl6>sub runrate($N where $N > 0, &todo) {
my $n = $N;
 
=={{header|Phix}}==
my $start = now;
On windows, time() advances in ~0.015s increments, whereas on linux it is ~0.0000016s.
todo() while --$n;
<!--<syntaxhighlight lang="phix">-->
my $end = now;
<span style="color: #008080;">procedure</span> <span style="color: #000000;">task_to_measure</span><span style="color: #0000FF;">()</span>
 
<span style="color: #7060A8;">sleep</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0.1</span><span style="color: #0000FF;">)</span>
say "Start time: ", DateTime.new($start).Str;
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
say "End time: ", DateTime.new($end).Str;
my $elapsed = $end - $start;
<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>
 
<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>
say "Elapsed time: $elapsed seconds";
<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>
say "Rate: { ($N / $elapsed).fmt('%.2f') } per second\n";
<span style="color: #000000;">task_to_measure</span><span style="color: #0000FF;">()</span>
}
<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>
 
<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>
sub factorial($n) { (state @)[$n] //= $n < 2 ?? 1 !! $n * factorial($n-1) }
<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>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
runrate 10000, { state $n = 1; factorial($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>
runrate 10000, { state $n = 1; factorial($n++) }</lang>
<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>
<span style="color: #004080;">integer</span> <span style="color: #000000;">runs</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span>
<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>
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">task_to_measure</span><span style="color: #0000FF;">()</span>
<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>
<span style="color: #000000;">runs</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"rate = %d per second\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">runs</span><span style="color: #0000FF;">)</span>
<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.
<pre>Start time: 2013-03-08T20:57:02Z
<pre>
End time: 2013-03-08T20:57:03Z
method 1: calculate reciprocal of elapsed time:
Elapsed time: 1.5467497 seconds
Rate:rate 6465= 9.1717431 per second
rate = 9.09091 per second
rate = 9.17431 per second
method 2: count completed tasks in one second:
rate = 9 per second
rate = 9 per second
rate = 9 per second
</pre>
 
=={{header|Phixmonti}}==
Start time: 2013-03-08T20:57:03Z
<syntaxhighlight lang="phixmonti">100000 var iterations
End time: 2013-03-08T20:57:04Z
2 4 2 tolist
Elapsed time: 0.7036318 seconds
for
Rate: 14211.98 per second</pre>
msec var a
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.
iterations
for
over 2 power + drop
endfor
msec a - var dif
"take " print dif print " secs" print
" or " print iterations dif / print " sums per second" print nl
endfor</syntaxhighlight>
 
=={{header|PicoLisp}}==
Line 1,015 ⟶ 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,022 ⟶ 1,690:
(key)
(prinl)
(prinl "This took " (format (- (usec) Usec) 6) " seconds") )</langsyntaxhighlight>
Output:
<pre>Hit a key ...
Line 1,029 ⟶ 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">
[datetime]$start = Get-Date
 
[int]$count = 3
 
[timespan[]]$times = for ($i = 0; $i -lt $count; $i++)
{
Measure-Command {0..999999 | Out-Null}
}
 
[datetime]$end = Get-Date
 
$rate = [PSCustomObject]@{
StartTime = $start
EndTime = $end
Duration = ($end - $start).TotalSeconds
TimesRun = $count
AverageRunTime = ($times.TotalSeconds | Measure-Object -Average).Average
}
 
$rate | Format-List
</syntaxhighlight>
{{Out}}
<pre>
StartTime : 10/27/2016 3:33:16 PM
EndTime : 10/27/2016 3:33:30 PM
Duration : 13.9062588
TimesRun : 3
AverageRunTime : 4.63301593333333
</pre>
 
=={{header|PureBasic}}==
===Counting frequence of an event===
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.d TimesPSec(Reset=#False)
Static starttime, cnt
Protected Result.d, dt
Line 1,069 ⟶ 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,084 ⟶ 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,144 ⟶ 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,150 ⟶ 1,850:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 1,163 ⟶ 1,863:
;; But of course, can be used to measure external processes too:
(time* 10 (system "sleep 1"))
</syntaxhighlight>
</lang>
 
Sample output:
Line 1,194 ⟶ 1,894:
#t
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub runrate($N where $N > 0, &todo) {
my $n = $N;
 
my $start = now;
todo() while --$n;
my $end = now;
 
say "Start time: ", DateTime.new($start).Str;
say "End time: ", DateTime.new($end).Str;
my $elapsed = $end - $start;
 
say "Elapsed time: $elapsed seconds";
say "Rate: { ($N / $elapsed).fmt('%.2f') } per second\n";
}
 
sub factorial($n) { (state @)[$n] //= $n < 2 ?? 1 !! $n * factorial($n-1) }
 
runrate 100_000, { state $n = 1; factorial($n++) }
 
runrate 100_000, { state $n = 1; factorial($n++) }</syntaxhighlight>
{{out}}
<pre>Start time: 2023-04-19T08:23:50.276418Z
End time: 2023-04-19T08:23:54.716864Z
Elapsed time: 4.440445313 seconds
Rate: 22520.26 per second
 
Start time: 2023-04-19T08:23:54.726913Z
End time: 2023-04-19T08:23:54.798238Z
Elapsed time: 0.071324057 seconds
Rate: 1402051.48 per second
</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.
 
=={{header|REXX}}==
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,232 ⟶ 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,401 ⟶ 2,136:
time used for task 3 was 0 seconds.
time used for task 4 was 0 seconds.
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Rate counter
 
see "method 1: calculate reciprocal of elapsed time:" + nl
for trial = 1 to 3
start = clock()
tasktomeasure()
finish = clock()
see "rate = " + 100 / (finish-start) + " per second" + nl
next
 
see "method 2: count completed tasks in one second:" + nl
for trial = 1 to 3
runs = 0
finish = clock() + 100
while clock() < finish
tasktomeasure()
if clock() < finish
runs = runs + 1
ok
end
see "rate = " + runs + " per second" + nl
next
func tasktomeasure
for i = 1 to 100000
next
</syntaxhighlight>
Output:
<pre>
method 1: calculate reciprocal of elapsed time:
rate = 6.67 per second
rate = 6.25 per second
rate = 6.67 per second
method 2: count completed tasks in one second:
rate = 5 per second
rate = 6 per second
rate = 5 per second
</pre>
 
=={{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,419 ⟶ 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</syntaxhighlight>
end
 
</lang>
System: I7-6700HQ, 3.5 GHz, Linux Kernel 5.6.17, Ruby 2.7.1
Run as: $ ruby ratecounter.rb
{{Output}}
<pre>
user system total real
array 41 0.660000308848 0.000000037154 41 0.660000346002 ( 41 0.692570158290)
hash 0.020000005239 0.000000001036 0.020000006275 ( 0.013756002252)
➜ rosettacode
 
</pre>
 
=={{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,473 ⟶ 2,253:
cpsi = cosi + cos(i)
next
end function </langsyntaxhighlight>
Output:
 
Line 1,500 ⟶ 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,511 ⟶ 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,518 ⟶ 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,532 ⟶ 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,546 ⟶ 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,561 ⟶ 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,576 ⟶ 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,586 ⟶ 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,609 ⟶ 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}}==
{{trans|Kotlin}}
For bench-marking purposes, Wren uses the ''System.clock'' method which returns the number of seconds (to 6 decimal places) since the script was started.
 
The precision of ''System.clock'' is not documented but since it calls C's ''clock()'' function in <timer.h> in the background it will certainly be no more than 1 microsecond and, in practice, resolution may be no better than 10 milliseconds on many systems.
 
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.
<syntaxhighlight lang="wren">var cube = Fn.new { |n| n * n * n }
 
var benchmark = Fn.new { |n, func, arg, calls|
var times = List.filled(n, 0)
for (i in 0...n) {
var m = System.clock
for (j in 0...calls) func.call(arg)
times[i] = ((System.clock - m) * 1000).round // milliseconds
}
return times
}
 
System.print("Timings (milliseconds) : ")
for (time in benchmark.call(10, cube, 5, 1e6)) System.print(time)</syntaxhighlight>
 
{{out}}
Sample run:
<pre>
Timings (milliseconds) :
55
48
45
45
45
45
45
45
45
46
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int N, I, T0, Time;
[for N:= 1, 3 do
Line 1,624 ⟶ 2,499:
RlOut(0, 100.0e6/float(Time)); Text(0, "Hz"); CrLf(0);
];
]</langsyntaxhighlight>
 
Example output of vertical blanking (screen refresh) rates:
Line 1,651 ⟶ 2,526:
</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">iterations = 100000
 
for j = 2 to 4
a = peek("millisrunning")
for i = 1 to iterations
void = i + j^2
next
dif = peek("millisrunning") - a
print "take ", dif, " ms";
print " or ", iterations / dif * 1000 using "########", " sums per second"
next</syntaxhighlight>
 
=={{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 1,671 ⟶ 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