Rate counter: Difference between revisions

Content added Content deleted
No edit summary
m (syntax highlighting fixup automation)
Line 14: Line 14:
=={{header|Action!}}==
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<lang Action!>INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit


DEFINE PTR="CARD"
DEFINE PTR="CARD"
Line 117: Line 117:
PrintF("Action%B: %U ms, %U times per sec%E",i+1,times(i),rate)
PrintF("Action%B: %U ms, %U times per sec%E",i+1,times(i),rate)
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Rate_counter.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Rate_counter.png Screenshot from Atari 8-bit computer]
Line 133: Line 133:
to get CPU times would use the package Ada.Execution_Time (Ada05).<br>
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.
The precision of measure is given by the value of System.Tick; on Windows value is 10 ms.
<lang Ada>with System; use System;
<syntaxhighlight lang="ada">with System; use System;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Calendar; use Ada.Calendar;
with Ada.Calendar; use Ada.Calendar;
Line 203: Line 203:
end loop;
end loop;


end Rate_Counter;</lang>
end Rate_Counter;</syntaxhighlight>


Output on a Linux 64 bits system:
Output on a Linux 64 bits system:
Line 219: Line 219:
===Built in variable===
===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.
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.
<lang AutoHotkey>SetBatchLines, -1
<syntaxhighlight lang="autohotkey">SetBatchLines, -1
Tick := A_TickCount ; store tickcount
Tick := A_TickCount ; store tickcount
Loop, 1000000 {
Loop, 1000000 {
Line 233: Line 233:
t := b, b := Mod(a, b), a := t
t := b, b := Mod(a, b), a := t
return, a
return, a
}</lang>
}</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>4.250000 Seconds elapsed.
<pre>4.250000 Seconds elapsed.
Line 240: Line 240:
===Query Performance Counter===
===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.
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.
<lang AutoHotkey>SetBatchLines, -1
<syntaxhighlight lang="autohotkey">SetBatchLines, -1
QPX(1) ; start timer
QPX(1) ; start timer
Loop, 1000000 {
Loop, 1000000 {
Line 262: Line 262:
t := b, b := Mod(a, b), a := t
t := b, b := Mod(a, b), a := t
return, a
return, a
}</lang>
}</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>4.428430 Seconds elapsed.
<pre>4.428430 Seconds elapsed.
Line 270: Line 270:
The TIMER builtin returns the elapsed time since start of program run, in milliseconds.
The TIMER builtin returns the elapsed time since start of program run, in milliseconds.


<lang freebasic>' Rate counter
<syntaxhighlight lang="freebasic">' Rate counter
FOR i = 1 TO 3
FOR i = 1 TO 3
GOSUB timeit
GOSUB timeit
Line 287: Line 287:
WEND
WEND
PRINT iter, " iterations in ", i, " millisecond", IIF$(i > 1, "s", "")
PRINT iter, " iterations in ", i, " millisecond", IIF$(i > 1, "s", "")
RETURN</lang>
RETURN</syntaxhighlight>


{{out}}
{{out}}
Line 299: Line 299:
=={{header|BASIC256}}==
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
<lang BASIC256>
global i
global i
subroutine timeit()
subroutine timeit()
Line 319: Line 319:
call timeit()
call timeit()
end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 331: Line 331:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> PRINT "Method 1: Calculate reciprocal of elapsed time:"
<syntaxhighlight lang="bbcbasic"> PRINT "Method 1: Calculate reciprocal of elapsed time:"
FOR trial% = 1 TO 3
FOR trial% = 1 TO 3
start% = TIME
start% = TIME
Line 356: Line 356:
FOR i% = 1 TO 1000000
FOR i% = 1 TO 1000000
NEXT
NEXT
ENDPROC</lang>
ENDPROC</syntaxhighlight>
'''Sample output:'''
'''Sample output:'''
<pre>
<pre>
Line 373: Line 373:
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.
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.


<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <time.h>
#include <time.h>


Line 446: Line 446:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{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.
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.


<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <ctime>
#include <ctime>


Line 528: Line 528:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Common Lisp already has a <code>time</code> macro.
Common Lisp already has a <code>time</code> macro.
<lang lisp>(time (do some stuff))</lang> will give a timing report about "stuff" on the trace output. We can define something similar with repeats:
<syntaxhighlight lang="lisp">(time (do some stuff))</syntaxhighlight> will give a timing report about "stuff" on the trace output. We can define something similar with repeats:
<lang lisp>(defmacro time-this (cnt &rest body)
<syntaxhighlight lang="lisp">(defmacro time-this (cnt &rest body)
(let ((real-t (gensym)) (run-t (gensym)))
(let ((real-t (gensym)) (run-t (gensym)))
`(let (,real-t ,run-t)
`(let (,real-t ,run-t)
Line 542: Line 542:
(coerce internal-time-units-per-second 'float))
(coerce internal-time-units-per-second 'float))
(/ (- (get-internal-run-time) ,run-t)
(/ (- (get-internal-run-time) ,run-t)
(coerce internal-time-units-per-second 'float))))))</lang>
(coerce internal-time-units-per-second 'float))))))</syntaxhighlight>


Call the <code>time-this</code> macro to excute a loop 99 times:
Call the <code>time-this</code> macro to excute a loop 99 times:
<lang lisp>(print (time-this 99 (loop for i below 10000 sum i)))</lang>which gives a pair of numbers, the real time and the run time, both in seconds:<lang>(0.023 0.022)</lang>
<syntaxhighlight lang="lisp">(print (time-this 99 (loop for i below 10000 sum i)))</syntaxhighlight>which gives a pair of numbers, the real time and the run time, both in seconds:<syntaxhighlight lang="text">(0.023 0.022)</syntaxhighlight>


=={{header|Crystal}}==
=={{header|Crystal}}==
{{trans|Ruby}}
{{trans|Ruby}}
Testing lookup speed in array versus hash:
Testing lookup speed in array versus hash:
<lang ruby>require "benchmark"
<syntaxhighlight lang="ruby">require "benchmark"


struct Document
struct Document
Line 576: Line 576:
x.report("array"){searchlist.each{ |el| documents_a.any?{ |d| d == el }} }
x.report("array"){searchlist.each{ |el| documents_a.any?{ |d| d == el }} }
x.report("hash") {searchlist.each{ |el| documents_h.has_key?(el) } }
x.report("hash") {searchlist.each{ |el| documents_h.has_key?(el) } }
end</lang>
end</syntaxhighlight>


System: I7-6700HQ, 3.5 GHz, Linux Kernel 5.6.17, Crystal 0.35
System: I7-6700HQ, 3.5 GHz, Linux Kernel 5.6.17, Crystal 0.35
Line 592: Line 592:
=={{header|D}}==
=={{header|D}}==


<syntaxhighlight lang="d">
<lang d>
import std.stdio;
import std.stdio;
import std.conv;
import std.conv;
Line 614: Line 614:
}
}


</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 629: Line 629:
{{libheader| System.Diagnostics}}
{{libheader| System.Diagnostics}}
{{Trans|D}}
{{Trans|D}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Rate_counter;
program Rate_counter;


Line 709: Line 709:
writeln('f', i, ': ', r[i]);
writeln('f', i, ': ', r[i]);
Readln;
Readln;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>Time fx took to run 10,000 times:
<pre>Time fx took to run 10,000 times:
Line 718: Line 718:


=={{header|E}}==
=={{header|E}}==
<lang e>def makeLamportSlot := <import:org.erights.e.elib.slot.makeLamportSlot>
<syntaxhighlight lang="e">def makeLamportSlot := <import:org.erights.e.elib.slot.makeLamportSlot>


The rate counter:
The rate counter:
Line 741: Line 741:
return [signal, &rate]
return [signal, &rate]
}</lang>
}</syntaxhighlight>


The test code:
The test code:


<lang e>/** Dummy task: Retrieve http://localhost/ and return the content. */
<syntaxhighlight lang="e">/** Dummy task: Retrieve http://localhost/ and return the content. */
def theJob() {
def theJob() {
return when (def text := <http://localhost/> <- getText()) -> {
return when (def text := <http://localhost/> <- getText()) -> {
Line 778: Line 778:
signal()
signal()
theJob()
theJob()
})</lang>
})</syntaxhighlight>


=={{header|Erlang}}==
=={{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.
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 ).
-module( rate_counter ).


Line 816: Line 816:
end.
end.


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 828: Line 828:


=={{header|ERRE}}==
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM RATE_COUNTER
PROGRAM RATE_COUNTER


Line 864: Line 864:
END FOR
END FOR
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
Time elapsed is measured with TIMER function (taken from computer clock).
Time elapsed is measured with TIMER function (taken from computer clock).
{{out}}
{{out}}
Line 883: Line 883:
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.
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 <lang Fortran> DO I = FIRST,LAST
So, in <syntaxhighlight lang="fortran"> DO I = FIRST,LAST
IF (PROGRESSNOTE((I - FIRST)/(LAST - FIRST + 1.0))) WRITE (6,*) "Reached ",I,", towards ",LAST
IF (PROGRESSNOTE((I - FIRST)/(LAST - FIRST + 1.0))) WRITE (6,*) "Reached ",I,", towards ",LAST
...much computation...
...much computation...
END DO</lang>
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,
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>
<pre>
Line 904: Line 904:
=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
{{trans|BaCon}}
{{trans|BaCon}}
<lang freebasic>
<syntaxhighlight lang="freebasic">
Dim Shared As Integer i
Dim Shared As Integer i


Line 923: Line 923:
i = 200 : timeit
i = 200 : timeit
Sleep
Sleep
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 935: Line 935:
=={{header|Go}}==
=={{header|Go}}==
{{trans|C}}
{{trans|C}}
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 986: Line 986:
latest = time.Now()
latest = time.Now()
}
}
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 996: Line 996:
=={{header|Haskell}}==
=={{header|Haskell}}==
This solution returns the time deltas in picosecond resolution.
This solution returns the time deltas in picosecond resolution.
<lang haskell>
<syntaxhighlight lang="haskell">
import Control.Monad
import Control.Monad
import Control.Concurrent
import Control.Concurrent
Line 1,019: Line 1,019:


main = timeit 10 (threadDelay 1000000)
main = timeit 10 (threadDelay 1000000)
</syntaxhighlight>
</lang>


=={{header|HicEst}}==
=={{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.
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.
<lang HicEst>CHARACTER prompt='Count "Hits++" for 5 sec, get current rate'
<syntaxhighlight lang="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)
DLG(Button="1:&Hits++", CALL="cb", B="2:&Count 5sec", B="3:&Rate", RC=retcod, TItle=prompt, WIN=hdl)
Line 1,042: Line 1,042:
SUBROUTINE F5 ! called 5 sec after button "5 sec"
SUBROUTINE F5 ! called 5 sec after button "5 sec"
WRITE(StatusBar) Hits, "hits last 5 sec"
WRITE(StatusBar) Hits, "hits last 5 sec"
END</lang>
END</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
'''Solution'''<br>
'''Solution'''<br>
<lang j> x (6!:2) y</lang>
<syntaxhighlight lang="j"> x (6!:2) y</syntaxhighlight>
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.
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:'''
'''Example:'''
<lang j> list=: 1e6 ?@$ 100 NB. 1 million random integers from 0 to 99
<syntaxhighlight lang="j"> list=: 1e6 ?@$ 100 NB. 1 million random integers from 0 to 99
freqtable=: ~. ,. #/.~ NB. verb to calculate and build frequency table
freqtable=: ~. ,. #/.~ NB. verb to calculate and build frequency table
20 (6!:2) 'freqtable list' NB. calculate and build frequency table for list, 20 times
20 (6!:2) 'freqtable list' NB. calculate and build frequency table for list, 20 times
0.00994106</lang>
0.00994106</syntaxhighlight>


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
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


<lang j> 1 1 1 (6!:2) 'freqtable list'
<syntaxhighlight lang="j"> 1 1 1 (6!:2) 'freqtable list'
0.0509995 0.0116702 0.0116266</lang>
0.0509995 0.0116702 0.0116266</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{trans|JavaScript}}
{{trans|JavaScript}}
{{works with|Java|8}}
{{works with|Java|8}}
<lang java>import java.util.function.Consumer;
<syntaxhighlight lang="java">import java.util.function.Consumer;


public class RateCounter {
public class RateCounter {
Line 1,081: Line 1,081:
return timings;
return timings;
}
}
}</lang>
}</syntaxhighlight>


<pre>70469.0
<pre>70469.0
Line 1,097: Line 1,097:
{{trans|JavaScript}}
{{trans|JavaScript}}
{{works with|Java|8}}
{{works with|Java|8}}
<lang java>import java.util.function.IntConsumer;
<syntaxhighlight lang="java">import java.util.function.IntConsumer;
import java.util.stream.DoubleStream;
import java.util.stream.DoubleStream;


Line 1,129: Line 1,129:
;
;
}
}
}</lang>
}</syntaxhighlight>


<pre>81431.0
<pre>81431.0
Line 1,145: Line 1,145:
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.
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.


<lang javascript>function millis() { // Gets current time in milliseconds.
<syntaxhighlight lang="javascript">function millis() { // Gets current time in milliseconds.
return (new Date()).getTime();
return (new Date()).getTime();
}
}
Line 1,158: Line 1,158:
}
}
return times;
return times;
}</lang>
}</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
<lang javascript>#!/usr/bin/env jsish
<syntaxhighlight lang="javascript">#!/usr/bin/env jsish
"use strict";
"use strict";
/* Rate counter, timer access, in Jsish */
/* Rate counter, timer access, in Jsish */
Line 1,180: Line 1,180:
timer = times(sleeper, 100);
timer = times(sleeper, 100);
puts(timer, 'μs to sleep 10 ms, 100 times');
puts(timer, 'μs to sleep 10 ms, 100 times');
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,192: Line 1,192:
=={{header|Julia}}==
=={{header|Julia}}==
The elapsed() macro in Julia generally is accurate in the nanosecond range.
The elapsed() macro in Julia generally is accurate in the nanosecond range.
<lang julia>dosomething() = sleep(abs(randn()))
<syntaxhighlight lang="julia">dosomething() = sleep(abs(randn()))


function runNsecondsworthofjobs(N)
function runNsecondsworthofjobs(N)
Line 1,213: Line 1,213:


runNsecondsworthofjobs(5)
runNsecondsworthofjobs(5)
</lang>{{output}}<pre> Ran job 5 times, for total time of 5.215301074 seconds.
</syntaxhighlight>{{output}}<pre> Ran job 5 times, for total time of 5.215301074 seconds.
Average time per run was 1.0430602148 seconds.
Average time per run was 1.0430602148 seconds.
Individual times of the jobs in seconds were:
Individual times of the jobs in seconds were:
Line 1,225: Line 1,225:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|JavaScript}}
{{trans|JavaScript}}
<lang scala>// version 1.1.3
<syntaxhighlight lang="scala">// version 1.1.3


typealias Func<T> = (T) -> T
typealias Func<T> = (T) -> T
Line 1,244: Line 1,244:
println("\nTimings (nanoseconds) : ")
println("\nTimings (nanoseconds) : ")
for (time in benchmark(10, ::cube, 5)) println(time)
for (time in benchmark(10, ::cube, 5)) println(time)
}</lang>
}</syntaxhighlight>


Sample output:
Sample output:
Line 1,262: Line 1,262:
=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
precision depends on OS. It is 16 (sometines cames as 15) ms for XP and 10 ms for Win2000.
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 "Rate counter"
print "Precision: system clock, ms ";
print "Precision: system clock, ms ";
Line 1,319: Line 1,319:
testFunc = s
testFunc = s
end function
end function
</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
The first parameter for both of these functions can be any program code.
The first parameter for both of these functions can be any program code.
<lang>jobRateCounted[fn_,Y_Integer]:=First[AbsoluteTiming[Do[fn,{Y}]]/Y;
<syntaxhighlight lang="text">jobRateCounted[fn_,Y_Integer]:=First[AbsoluteTiming[Do[fn,{Y}]]/Y;
SetAttributes[jobRateCounted,HoldFirst]
SetAttributes[jobRateCounted,HoldFirst]
jobRatePeriod[fn_,time_]:=Block[{n=0},TimeConstrained[While[True,fn;n++]];n/time];
jobRatePeriod[fn_,time_]:=Block[{n=0},TimeConstrained[While[True,fn;n++]];n/time];
SetAttributes[jobRatePeriod,HoldFirst]</lang>
SetAttributes[jobRatePeriod,HoldFirst]</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang Nim>import sugar, std/monotimes, times
<syntaxhighlight lang="nim">import sugar, std/monotimes, times


type Func[T] = (T) -> T
type Func[T] = (T) -> T
Line 1,345: Line 1,345:
echo "Timings (nanoseconds):"
echo "Timings (nanoseconds):"
for time in benchmark(10, cube, 5):
for time in benchmark(10, cube, 5):
echo time.inNanoseconds</lang>
echo time.inNanoseconds</syntaxhighlight>


{{out}}
{{out}}
Line 1,362: Line 1,362:
=={{header|OxygenBasic}}==
=={{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.
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.
<lang oxygenbasic>
<syntaxhighlight lang="oxygenbasic">
'========
'========
'TIME API
'TIME API
Line 1,481: Line 1,481:
'Finish: 2012-07-01 00:52:36:974
'Finish: 2012-07-01 00:52:36:974
'Sunday July 01 2012
'Sunday July 01 2012
</syntaxhighlight>
</lang>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>a=0;
<syntaxhighlight lang="parigp">a=0;
b=0;
b=0;
for(n=1,20000000,
for(n=1,20000000,
Line 1,493: Line 1,493:
a=a+gettime();
a=a+gettime();
if(a>60000,print(b);a=0;b=0)
if(a>60000,print(b);a=0;b=0)
)</lang>
)</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
The [http://perldoc.perl.org/Benchmark.html Benchmark] module can rate code per time, or per loops executed:
The [http://perldoc.perl.org/Benchmark.html Benchmark] module can rate code per time, or per loops executed:
<lang perl>use Benchmark;
<syntaxhighlight lang="perl">use Benchmark;


timethese COUNT,{ 'Job1' => &job1, 'Job2' => &job2 };
timethese COUNT,{ 'Job1' => &job1, 'Job2' => &job2 };
Line 1,508: Line 1,508:
{
{
...job2 code...
...job2 code...
}</lang>
}</syntaxhighlight>
A negative COUNT will run each job for at least COUNT seconds.<br>
A negative COUNT will run each job for at least COUNT seconds.<br>
A positive COUNT will run each job COUNT times.
A positive COUNT will run each job COUNT times.
Line 1,514: Line 1,514:
=={{header|Phix}}==
=={{header|Phix}}==
On windows, time() advances in ~0.015s increments, whereas on linux it is ~0.0000016s.
On windows, time() advances in ~0.015s increments, whereas on linux it is ~0.0000016s.
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">procedure</span> <span style="color: #000000;">task_to_measure</span><span style="color: #0000FF;">()</span>
<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>
<span style="color: #7060A8;">sleep</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0.1</span><span style="color: #0000FF;">)</span>
Line 1,539: Line 1,539:
<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: #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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
Of course it fails to achieve the perfect 10/s, due to the overhead of call/ret/time/printf etc.
Of course it fails to achieve the perfect 10/s, due to the overhead of call/ret/time/printf etc.
Line 1,554: Line 1,554:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>100000 var iterations
<syntaxhighlight lang="phixmonti">100000 var iterations
2 4 2 tolist
2 4 2 tolist
for
for
Line 1,565: Line 1,565:
"take " print dif print " secs" print
"take " print dif print " secs" print
" or " print iterations dif / print " sums per second" print nl
" or " print iterations dif / print " sums per second" print nl
endfor</lang>
endfor</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
Line 1,571: Line 1,571:
microseconds. This can be used, for example, to measure the time between two key
microseconds. This can be used, for example, to measure the time between two key
strokes
strokes
<lang PicoLisp>(prin "Hit a key ... ")
<syntaxhighlight lang="picolisp">(prin "Hit a key ... ")
(key)
(key)
(prinl)
(prinl)
Line 1,578: Line 1,578:
(key)
(key)
(prinl)
(prinl)
(prinl "This took " (format (- (usec) Usec) 6) " seconds") )</lang>
(prinl "This took " (format (- (usec) Usec) 6) " seconds") )</syntaxhighlight>
Output:
Output:
<pre>Hit a key ...
<pre>Hit a key ...
Line 1,585: Line 1,585:
The [http://software-lab.de/doc/refB.html#bench bench] benchmark function could
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
also be used. Here we measure the time until a key is pressed
<lang PicoLisp>(bench (key))</lang>
<syntaxhighlight lang="picolisp">(bench (key))</syntaxhighlight>
<pre>1.761 sec
<pre>1.761 sec
-> "a"</pre>
-> "a"</pre>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
[datetime]$start = Get-Date
[datetime]$start = Get-Date


Line 1,611: Line 1,611:


$rate | Format-List
$rate | Format-List
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,623: Line 1,623:
=={{header|PureBasic}}==
=={{header|PureBasic}}==
===Counting frequence of an event===
===Counting frequence of an event===
<lang PureBasic>Procedure.d TimesPSec(Reset=#False)
<syntaxhighlight lang="purebasic">Procedure.d TimesPSec(Reset=#False)
Static starttime, cnt
Static starttime, cnt
Protected Result.d, dt
Protected Result.d, dt
Line 1,657: Line 1,657:
EndIf
EndIf
Until Event=#PB_Event_CloseWindow
Until Event=#PB_Event_CloseWindow
EndIf</lang>
EndIf</syntaxhighlight>


===Counting events for a time period===
===Counting events for a time period===
<lang PureBasic>Procedure DummyThread(arg)
<syntaxhighlight lang="purebasic">Procedure DummyThread(arg)
Define.d dummy=#PI*Pow(arg,2)/4
Define.d dummy=#PI*Pow(arg,2)/4
EndProcedure
EndProcedure
Line 1,672: Line 1,672:


msg$="We got "+Str(cnt)+" st."+Chr(10)+StrF(cnt/10,2)+" threads per sec."
msg$="We got "+Str(cnt)+" st."+Chr(10)+StrF(cnt/10,2)+" threads per sec."
MessageRequester("Counting threads in 10 sec",msg$)</lang>
MessageRequester("Counting threads in 10 sec",msg$)</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>import subprocess
<syntaxhighlight lang="python">import subprocess
import time
import time


Line 1,732: Line 1,732:
taskTimer( int(sys.argv[1]), sys.argv[2:])
taskTimer( int(sys.argv[1]), sys.argv[2:])


main()</lang>
main()</syntaxhighlight>
Usage Example:
Usage Example:
First argument is the number of times to iterate. Additional arguments are command to execute.
First argument is the number of times to iterate. Additional arguments are command to execute.
Line 1,738: Line 1,738:


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket


Line 1,751: Line 1,751:
;; But of course, can be used to measure external processes too:
;; But of course, can be used to measure external processes too:
(time* 10 (system "sleep 1"))
(time* 10 (system "sleep 1"))
</syntaxhighlight>
</lang>


Sample output:
Sample output:
Line 1,785: Line 1,785:
=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>sub runrate($N where $N > 0, &todo) {
<syntaxhighlight lang="raku" line>sub runrate($N where $N > 0, &todo) {
my $n = $N;
my $n = $N;


Line 1,804: Line 1,804:
runrate 10000, { state $n = 1; factorial($n++) }
runrate 10000, { state $n = 1; factorial($n++) }


runrate 10000, { state $n = 1; factorial($n++) }</lang>
runrate 10000, { state $n = 1; factorial($n++) }</syntaxhighlight>
{{out}}
{{out}}
<pre>Start time: 2013-03-08T20:57:02Z
<pre>Start time: 2013-03-08T20:57:02Z
Line 1,820: Line 1,820:
Programming note: &nbsp; The &nbsp; '''$CALC''' &nbsp; (REXX) program which is invoked below is a general purpose calculator which supports a multitude
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).
<br>of functions (over 1,500), &nbsp; and can show the results in many different formats &nbsp; (some of which are shown here).
<lang rexx>/*REXX program reports on the amount of elapsed time 4 different tasks use (wall clock).*/
<syntaxhighlight 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*/
time.= /*nullify times for all the tasks below*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
Line 1,854: Line 1,854:
say 'time used for task' j "was" right(format(time.j,,0),4) 'seconds.'
say 'time used for task' j "was" right(format(time.j,,0),4) 'seconds.'
end /*j*/
end /*j*/
/*stick a fork in it, we're all done. */</lang>
/*stick a fork in it, we're all done. */</syntaxhighlight>
'''output''' &nbsp; (of the tasks as well as the above REXX timer program):
'''output''' &nbsp; (of the tasks as well as the above REXX timer program):


Line 2,026: Line 2,026:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Rate counter
# Project : Rate counter


Line 2,053: Line 2,053:
for i = 1 to 100000
for i = 1 to 100000
next
next
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,068: Line 2,068:
=={{header|Ruby}}==
=={{header|Ruby}}==
Testing lookup speed in array versus hash:
Testing lookup speed in array versus hash:
<lang ruby>require 'benchmark'
<syntaxhighlight lang="ruby">require 'benchmark'
Document = Struct.new(:id,:a,:b,:c)
Document = Struct.new(:id,:a,:b,:c)
documents_a = []
documents_a = []
Line 2,082: Line 2,082:
x.report('array'){searchlist.each{|el| documents_a.any?{|d| d.id == el}} }
x.report('array'){searchlist.each{|el| documents_a.any?{|d| d.id == el}} }
x.report('hash'){searchlist.each{|el| documents_h.has_key?(el)} }
x.report('hash'){searchlist.each{|el| documents_h.has_key?(el)} }
end</lang>
end</syntaxhighlight>


System: I7-6700HQ, 3.5 GHz, Linux Kernel 5.6.17, Ruby 2.7.1
System: I7-6700HQ, 3.5 GHz, Linux Kernel 5.6.17, Ruby 2.7.1
Line 2,096: Line 2,096:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>html "<table bgcolor=wheat border=1><tr><td align=center colspan=2>Rate Counter</td></tr>
<syntaxhighlight 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>"
<tr><td>Run Job Times</td><td>"
textbox #runTimes,"10",3
textbox #runTimes,"10",3
Line 2,140: Line 2,140:
cpsi = cosi + cos(i)
cpsi = cosi + cos(i)
next
next
end function </lang>
end function </syntaxhighlight>
Output:
Output:


Line 2,167: Line 2,167:
once the time is up.
once the time is up.


<lang scala>def task(n: Int) = Thread.sleep(n * 1000)
<syntaxhighlight lang="scala">def task(n: Int) = Thread.sleep(n * 1000)
def rate(fs: List[() => Unit]) = {
def rate(fs: List[() => Unit]) = {
val jobs = fs map (f => scala.actors.Futures.future(f()))
val jobs = fs map (f => scala.actors.Futures.future(f()))
Line 2,178: Line 2,178:
}
}
rate(List.fill(30)(() => task(scala.util.Random.nextInt(10)+1)))
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
The solution below runs a task repeatedly, for at most N seconds or Y times. The
Line 2,185: Line 2,185:
result, if the time runs out.
result, if the time runs out.


<lang scala>def rate(n: Int, y: Int)(task: => Unit) {
<syntaxhighlight lang="scala">def rate(n: Int, y: Int)(task: => Unit) {
val startTime = System.currentTimeMillis
val startTime = System.currentTimeMillis
var currTime = startTime
var currTime = startTime
Line 2,199: Line 2,199:
println("Rate %d times in %.3f seconds" format (y, (currTime - startTime).toDouble / 1000))
println("Rate %d times in %.3f seconds" format (y, (currTime - startTime).toDouble / 1000))
}
}
rate(5, 20)(task(2))</lang>
rate(5, 20)(task(2))</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Perl}}
{{trans|Perl}}
<lang ruby>var benchmark = frequire('Benchmark');
<syntaxhighlight lang="ruby">var benchmark = frequire('Benchmark');


func job1 {
func job1 {
Line 2,213: Line 2,213:


const COUNT = -1; # run for one CPU second
const COUNT = -1; # run for one CPU second
benchmark.timethese(COUNT, Hash.new('Job1' => job1, 'Job2' => job2));</lang>
benchmark.timethese(COUNT, Hash.new('Job1' => job1, 'Job2' => job2));</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|Pharo}}
{{works with|Pharo}}
{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
<lang smalltalk>|times|
<syntaxhighlight lang="smalltalk">|times|
times := Bag new.
times := Bag new.
1 to: 10 do: [:n| times add:
1 to: 10 do: [:n| times add:
(Time millisecondsToRun: [3000 factorial])].
(Time millisecondsToRun: [3000 factorial])].
Transcript show: times average asInteger.</lang>
Transcript show: times average asInteger.</syntaxhighlight>
Output:
Output:
<pre>153</pre>
<pre>153</pre>
Line 2,228: Line 2,228:
=={{header|Tcl}}==
=={{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.
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.
<lang tcl>set iters 10
<syntaxhighlight lang="tcl">set iters 10


# A silly example task
# A silly example task
Line 2,243: Line 2,243:
}] 0]
}] 0]
puts "task took $t microseconds on iteration $i"
puts "task took $t microseconds on iteration $i"
}</lang>
}</syntaxhighlight>
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).
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).
<lang tcl>puts [time { set aVar 123 } 1000000]</lang>
<syntaxhighlight lang="tcl">puts [time { set aVar 123 } 1000000]</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
Line 2,253: Line 2,253:
<br>
<br>
This script spins, executing '''task''' as many times as possible.
This script spins, executing '''task''' as many times as possible.
<lang bash>#!/bin/bash
<syntaxhighlight lang="bash">#!/bin/bash


while : ; do
while : ; do
task && echo >> .fc
task && echo >> .fc
done</lang>
done</syntaxhighlight>


Part 2:
Part 2:
<br>
<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.
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.
<lang bash>./foo.sh &
<syntaxhighlight lang="bash">./foo.sh &
sleep 5
sleep 5
mv .fc .fc2 2>/dev/null
mv .fc .fc2 2>/dev/null
Line 2,276: Line 2,276:
killall foo.sh
killall foo.sh
wc -l .fc 2>/dev/null
wc -l .fc 2>/dev/null
rm .fc</lang>
rm .fc</syntaxhighlight>


=={{header|Vlang}}==
=={{header|Vlang}}==
{{trans|Go}}
{{trans|Go}}
<lang vlang>import rand
<syntaxhighlight lang="vlang">import rand
import time
import time


Line 2,327: Line 2,327:
latest = time.now()
latest = time.now()
}
}
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 2,342: Line 2,342:


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.
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.
<lang ecmascript>var cube = Fn.new { |n| n * n * n }
<syntaxhighlight lang="ecmascript">var cube = Fn.new { |n| n * n * n }


var benchmark = Fn.new { |n, func, arg, calls|
var benchmark = Fn.new { |n, func, arg, calls|
Line 2,355: Line 2,355:


System.print("Timings (milliseconds) : ")
System.print("Timings (milliseconds) : ")
for (time in benchmark.call(10, cube, 5, 1e6)) System.print(time)</lang>
for (time in benchmark.call(10, cube, 5, 1e6)) System.print(time)</syntaxhighlight>


{{out}}
{{out}}
Line 2,374: Line 2,374:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int N, I, T0, Time;
int N, I, T0, Time;
[for N:= 1, 3 do
[for N:= 1, 3 do
Line 2,386: Line 2,386:
RlOut(0, 100.0e6/float(Time)); Text(0, "Hz"); CrLf(0);
RlOut(0, 100.0e6/float(Time)); Text(0, "Hz"); CrLf(0);
];
];
]</lang>
]</syntaxhighlight>


Example output of vertical blanking (screen refresh) rates:
Example output of vertical blanking (screen refresh) rates:
Line 2,414: Line 2,414:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>iterations = 100000
<syntaxhighlight lang="yabasic">iterations = 100000


for j = 2 to 4
for j = 2 to 4
Line 2,424: Line 2,424:
print "take ", dif, " ms";
print "take ", dif, " ms";
print " or ", iterations / dif * 1000 using "########", " sums per second"
print " or ", iterations / dif * 1000 using "########", " sums per second"
next</lang>
next</syntaxhighlight>


=={{header|zkl}}==
=={{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.
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.
<lang zkl>fcn rateCounter(f,timeNRuns,secsToRun=Void){
<syntaxhighlight lang="zkl">fcn rateCounter(f,timeNRuns,secsToRun=Void){
now:=Time.Clock.time;
now:=Time.Clock.time;
if(secsToRun){
if(secsToRun){
Line 2,445: Line 2,445:
t
t
}
}
}</lang>
}</syntaxhighlight>
<lang zkl>ns:=List.createLong(0d100_000,(0).random,True); // one hundred thousand ints
<syntaxhighlight 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() },20);
rateCounter('wrap(){ ns.copy().sort() },Void,10);</lang>
rateCounter('wrap(){ ns.copy().sort() },Void,10);</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>