Rate counter: Difference between revisions
m
syntax highlighting fixup automation
No edit summary |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 14:
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<
DEFINE PTR="CARD"
Line 117:
PrintF("Action%B: %U ms, %U times per sec%E",i+1,times(i),rate)
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Rate_counter.png Screenshot from Atari 8-bit computer]
Line 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.
<
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Calendar; use Ada.Calendar;
Line 203:
end loop;
end Rate_Counter;</
Output on a Linux 64 bits system:
Line 219:
===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.
<
Tick := A_TickCount ; store tickcount
Loop, 1000000 {
Line 233:
t := b, b := Mod(a, b), a := t
return, a
}</
'''Output:'''
<pre>4.250000 Seconds elapsed.
Line 240:
===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.
<
QPX(1) ; start timer
Loop, 1000000 {
Line 262:
t := b, b := Mod(a, b), a := t
return, a
}</
'''Output:'''
<pre>4.428430 Seconds elapsed.
Line 270:
The TIMER builtin returns the elapsed time since start of program run, in milliseconds.
<
FOR i = 1 TO 3
GOSUB timeit
Line 287:
WEND
PRINT iter, " iterations in ", i, " millisecond", IIF$(i > 1, "s", "")
RETURN</
{{out}}
Line 299:
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
global i
subroutine timeit()
Line 319:
call timeit()
end
</syntaxhighlight>
{{out}}
<pre>
Line 331:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
FOR trial% = 1 TO 3
start% = TIME
Line 356:
FOR i% = 1 TO 1000000
NEXT
ENDPROC</
'''Sample output:'''
<pre>
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.
<
#include <time.h>
Line 446:
return 0;
}</
=={{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.
<
#include <ctime>
Line 528:
return 0;
}</
=={{header|Common Lisp}}==
Common Lisp already has a <code>time</code> macro.
<
<
(let ((real-t (gensym)) (run-t (gensym)))
`(let (,real-t ,run-t)
Line 542:
(coerce internal-time-units-per-second 'float))
(/ (- (get-internal-run-time) ,run-t)
(coerce internal-time-units-per-second 'float))))))</
Call the <code>time-this</code> macro to excute a loop 99 times:
<
=={{header|Crystal}}==
{{trans|Ruby}}
Testing lookup speed in array versus hash:
<
struct Document
Line 576:
x.report("array"){searchlist.each{ |el| documents_a.any?{ |d| d == el }} }
x.report("hash") {searchlist.each{ |el| documents_h.has_key?(el) } }
end</
System: I7-6700HQ, 3.5 GHz, Linux Kernel 5.6.17, Crystal 0.35
Line 592:
=={{header|D}}==
<syntaxhighlight lang="d">
import std.stdio;
import std.conv;
Line 614:
}
</syntaxhighlight>
{{out}}
Line 629:
{{libheader| System.Diagnostics}}
{{Trans|D}}
<syntaxhighlight lang="delphi">
program Rate_counter;
Line 709:
writeln('f', i, ': ', r[i]);
Readln;
end.</
{{out}}
<pre>Time fx took to run 10,000 times:
Line 718:
=={{header|E}}==
<
The rate counter:
Line 741:
return [signal, &rate]
}</
The test code:
<
def theJob() {
return when (def text := <http://localhost/> <- getText()) -> {
Line 778:
signal()
theJob()
})</
=={{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">
-module( rate_counter ).
Line 816:
end.
</syntaxhighlight>
{{out}}
<pre>
Line 828:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM RATE_COUNTER
Line 864:
END FOR
END PROGRAM
</syntaxhighlight>
Time elapsed is measured with TIMER function (taken from computer clock).
{{out}}
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.
So, in <
IF (PROGRESSNOTE((I - FIRST)/(LAST - FIRST + 1.0))) WRITE (6,*) "Reached ",I,", towards ",LAST
...much computation...
END DO</
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 904:
=={{header|FreeBASIC}}==
{{trans|BaCon}}
<
Dim Shared As Integer i
Line 923:
i = 200 : timeit
Sleep
</syntaxhighlight>
{{out}}
<pre>
Line 935:
=={{header|Go}}==
{{trans|C}}
<
import (
Line 986:
latest = time.Now()
}
}</
Output:
<pre>
Line 996:
=={{header|Haskell}}==
This solution returns the time deltas in picosecond resolution.
<
import Control.Monad
import Control.Concurrent
Line 1,019:
main = timeit 10 (threadDelay 1000000)
</syntaxhighlight>
=={{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.
<
DLG(Button="1:&Hits++", CALL="cb", B="2:&Count 5sec", B="3:&Rate", RC=retcod, TItle=prompt, WIN=hdl)
Line 1,042:
SUBROUTINE F5 ! called 5 sec after button "5 sec"
WRITE(StatusBar) Hits, "hits last 5 sec"
END</
=={{header|J}}==
'''Solution'''<br>
<
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:'''
<
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</
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
<
0.0509995 0.0116702 0.0116266</
=={{header|Java}}==
{{trans|JavaScript}}
{{works with|Java|8}}
<
public class RateCounter {
Line 1,081:
return timings;
}
}</
<pre>70469.0
Line 1,097:
{{trans|JavaScript}}
{{works with|Java|8}}
<
import java.util.stream.DoubleStream;
Line 1,129:
;
}
}</
<pre>81431.0
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.
<
return (new Date()).getTime();
}
Line 1,158:
}
return times;
}</
=={{header|Jsish}}==
<
"use strict";
/* Rate counter, timer access, in Jsish */
Line 1,180:
timer = times(sleeper, 100);
puts(timer, 'μs to sleep 10 ms, 100 times');
}</
{{out}}
Line 1,192:
=={{header|Julia}}==
The elapsed() macro in Julia generally is accurate in the nanosecond range.
<
function runNsecondsworthofjobs(N)
Line 1,213:
runNsecondsworthofjobs(5)
</
Average time per run was 1.0430602148 seconds.
Individual times of the jobs in seconds were:
Line 1,225:
=={{header|Kotlin}}==
{{trans|JavaScript}}
<
typealias Func<T> = (T) -> T
Line 1,244:
println("\nTimings (nanoseconds) : ")
for (time in benchmark(10, ::cube, 5)) println(time)
}</
Sample output:
Line 1,262:
=={{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">
Print "Rate counter"
print "Precision: system clock, ms ";
Line 1,319:
testFunc = s
end function
</syntaxhighlight>
=={{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]</
=={{header|Nim}}==
{{trans|Kotlin}}
<
type Func[T] = (T) -> T
Line 1,345:
echo "Timings (nanoseconds):"
for time in benchmark(10, cube, 5):
echo time.inNanoseconds</
{{out}}
Line 1,362:
=={{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.
<
'========
'TIME API
Line 1,481:
'Finish: 2012-07-01 00:52:36:974
'Sunday July 01 2012
</syntaxhighlight>
=={{header|PARI/GP}}==
<
b=0;
for(n=1,20000000,
Line 1,493:
a=a+gettime();
if(a>60000,print(b);a=0;b=0)
)</
=={{header|Perl}}==
The [http://perldoc.perl.org/Benchmark.html Benchmark] module can rate code per time, or per loops executed:
<
timethese COUNT,{ 'Job1' => &job1, 'Job2' => &job2 };
Line 1,508:
{
...job2 code...
}</
A negative COUNT will run each job for at least COUNT seconds.<br>
A positive COUNT will run each job COUNT times.
Line 1,514:
=={{header|Phix}}==
On windows, time() advances in ~0.015s increments, whereas on linux it is ~0.0000016s.
<!--<
<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>
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: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
Of course it fails to achieve the perfect 10/s, due to the overhead of call/ret/time/printf etc.
Line 1,554:
=={{header|Phixmonti}}==
<
2 4 2 tolist
for
Line 1,565:
"take " print dif print " secs" print
" or " print iterations dif / print " sums per second" print nl
endfor</
=={{header|PicoLisp}}==
Line 1,571:
microseconds. This can be used, for example, to measure the time between two key
strokes
<
(key)
(prinl)
Line 1,578:
(key)
(prinl)
(prinl "This took " (format (- (usec) Usec) 6) " seconds") )</
Output:
<pre>Hit a key ...
Line 1,585:
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
<pre>1.761 sec
-> "a"</pre>
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
[datetime]$start = Get-Date
Line 1,611:
$rate | Format-List
</syntaxhighlight>
{{Out}}
<pre>
Line 1,623:
=={{header|PureBasic}}==
===Counting frequence of an event===
<
Static starttime, cnt
Protected Result.d, dt
Line 1,657:
EndIf
Until Event=#PB_Event_CloseWindow
EndIf</
===Counting events for a time period===
<
Define.d dummy=#PI*Pow(arg,2)/4
EndProcedure
Line 1,672:
msg$="We got "+Str(cnt)+" st."+Chr(10)+StrF(cnt/10,2)+" threads per sec."
MessageRequester("Counting threads in 10 sec",msg$)</
=={{header|Python}}==
<
import time
Line 1,732:
taskTimer( int(sys.argv[1]), sys.argv[2:])
main()</
Usage Example:
First argument is the number of times to iterate. Additional arguments are command to execute.
Line 1,738:
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
Line 1,751:
;; But of course, can be used to measure external processes too:
(time* 10 (system "sleep 1"))
</syntaxhighlight>
Sample output:
Line 1,785:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
my $n = $N;
Line 1,804:
runrate 10000, { state $n = 1; factorial($n++) }
runrate 10000, { state $n = 1; factorial($n++) }</
{{out}}
<pre>Start time: 2013-03-08T20:57:02Z
Line 1,820:
Programming note: The '''$CALC''' (REXX) program which is invoked below is a general purpose calculator which supports a multitude
<br>of functions (over 1,500), and can show the results in many different formats (some of which are shown here).
<
time.= /*nullify times for all the tasks below*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
Line 1,854:
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. */</
'''output''' (of the tasks as well as the above REXX timer program):
Line 2,026:
=={{header|Ring}}==
<
# Project : Rate counter
Line 2,053:
for i = 1 to 100000
next
</syntaxhighlight>
Output:
<pre>
Line 2,068:
=={{header|Ruby}}==
Testing lookup speed in array versus hash:
<
Document = Struct.new(:id,:a,:b,:c)
documents_a = []
Line 2,082:
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</
System: I7-6700HQ, 3.5 GHz, Linux Kernel 5.6.17, Ruby 2.7.1
Line 2,096:
=={{header|Run BASIC}}==
<
<tr><td>Run Job Times</td><td>"
textbox #runTimes,"10",3
Line 2,140:
cpsi = cosi + cos(i)
next
end function </
Output:
Line 2,167:
once the time is up.
<
def rate(fs: List[() => Unit]) = {
val jobs = fs map (f => scala.actors.Futures.future(f()))
Line 2,178:
}
rate(List.fill(30)(() => task(scala.util.Random.nextInt(10)+1)))
</syntaxhighlight>
The solution below runs a task repeatedly, for at most N seconds or Y times. The
Line 2,185:
result, if the time runs out.
<
val startTime = System.currentTimeMillis
var currTime = startTime
Line 2,199:
println("Rate %d times in %.3f seconds" format (y, (currTime - startTime).toDouble / 1000))
}
rate(5, 20)(task(2))</
=={{header|Sidef}}==
{{trans|Perl}}
<
func job1 {
Line 2,213:
const COUNT = -1; # run for one CPU second
benchmark.timethese(COUNT, Hash.new('Job1' => job1, 'Job2' => job2));</
=={{header|Smalltalk}}==
{{works with|Pharo}}
{{works with|Smalltalk/X}}
<
times := Bag new.
1 to: 10 do: [:n| times add:
(Time millisecondsToRun: [3000 factorial])].
Transcript show: times average asInteger.</
Output:
<pre>153</pre>
Line 2,228:
=={{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.
<
# A silly example task
Line 2,243:
}] 0]
puts "task took $t microseconds on iteration $i"
}</
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).
<
=={{header|UNIX Shell}}==
Line 2,253:
<br>
This script spins, executing '''task''' as many times as possible.
<
while : ; do
task && echo >> .fc
done</
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.
<
sleep 5
mv .fc .fc2 2>/dev/null
Line 2,276:
killall foo.sh
wc -l .fc 2>/dev/null
rm .fc</
=={{header|Vlang}}==
{{trans|Go}}
<
import time
Line 2,327:
latest = time.now()
}
}</
Output:
<pre>
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.
<
var benchmark = Fn.new { |n, func, arg, calls|
Line 2,355:
System.print("Timings (milliseconds) : ")
for (time in benchmark.call(10, cube, 5, 1e6)) System.print(time)</
{{out}}
Line 2,374:
=={{header|XPL0}}==
<
int N, I, T0, Time;
[for N:= 1, 3 do
Line 2,386:
RlOut(0, 100.0e6/float(Time)); Text(0, "Hz"); CrLf(0);
];
]</
Example output of vertical blanking (screen refresh) rates:
Line 2,414:
=={{header|Yabasic}}==
<
for j = 2 to 4
Line 2,424:
print "take ", dif, " ms";
print " or ", iterations / dif * 1000 using "########", " sums per second"
next</
=={{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.
<
now:=Time.Clock.time;
if(secsToRun){
Line 2,445:
t
}
}</
<
rateCounter('wrap(){ ns.copy().sort() },20);
rateCounter('wrap(){ ns.copy().sort() },Void,10);</
{{out}}
<pre>
|