Time a function: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (syntax highlighting fixup automation)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(22 intermediate revisions by 14 users not shown)
Line 833:
 
=={{header|C++}}==
===Using <code>ctime</code>===
<syntaxhighlight lang="cpp">#include <ctime>
#include <iostream>
Line 857 ⟶ 858:
}</syntaxhighlight>
 
Output:
===Example===
<pre>
Identity(4) takes 0 seconds.
Sum(4) takes 0.01 seconds.
</pre>
 
===Using <code>std::chrono</code>===
 
<syntaxhighlight lang="cpp">
// Compile with:
// g++ -std=c++20 -Wall -Wextra -pedantic -O0 func-time.cpp -o func-time
 
#include <iostream>
#include <chrono>
 
template<typename f>
double measure(f func) {
auto start = std::chrono::steady_clock::now(); // Starting point
(*func)(); // Run the function
auto end = std::chrono::steady_clock::now(); // End point
return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); // By default, return time by milliseconds
}
 
/*
Test functions:
identity(): returns a number
addmillion(): add 1,000,000 to a number, one by one, using a for-loop
*/
 
int identity(int x) { return x; }
 
int addmillion(int num) {
for (int i = 0; i < 1000000; i++)
num += i;
return num;
}
 
int main() {
double time;
time = measure([](){ return identity(10); });
// Shove the function into a lambda function.
// Yeah, I couldn't think of any better workaround.
std::cout << "identity(10)\t\t" << time << " milliseconds / " << time / 1000 << " seconds" << std::endl; // Print it
time = measure([](){ return addmillion(1800); });
std::cout << "addmillion(1800)\t" << time << " milliseconds / " << time / 1000 << " seconds" << std::endl;
return 0;
}
</syntaxhighlight>
 
Output:
<pre>
identity(10) 0 milliseconds / 0 seconds
addmillion(1800) 4 milliseconds / 0.004 seconds
</pre>
 
=={{header|Clojure}}==
Line 963 ⟶ 1,017:
}
</syntaxhighlight>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
[[File:DelphiTimerObject.png|frame|none]]
Here is a simple timer object that I use to time different parts of the code, to figure out which parts take the most time and are the best targets for optimization.
 
The object is based on the TPanel, which means the timer can be dropped on a form where it will display timing data whenever you want.
 
The time is controlled by four different commands: '''Reset, Start, Stop'''''Italic text'' and '''Display'''''Italic text''.
 
'''Reset'''. Reset zeros the timer.
'''Start'''. Starts the timer running.
'''Stop'''. Stops the timer.
'''Displays'''. Displays the current cumulative time since the first start.
 
Start and Stop can be moved around the code to control which parts are timed. You can even turn the timer on and off multiple times to messure the combined execution times of multiple different sections of code. You can also move the Start and Stop commands closer and closer together to zoom in on the part of the code that takes the most time to execute.
 
Finally, since the object is based on the TPanel component, the font, colors and layout can be made to look fancy for placement on the status bar of a program.
<syntaxhighlight lang="Delphi">
type TResolution=(rsSeconds,rsMiliSeconds);
 
type TCodeTimer=class(TPanel)
private
FResolution: TResolution;
public
WrkCount,TotCount: longint;
constructor Create(AOwner: TComponent); override;
procedure Reset;
procedure Start;
procedure Stop;
procedure Display;
published
property Resolution: TResolution read FResolution write FResolution default rsMiliSeconds;
end;
 
 
function GetHiResTick: integer;
var C: TLargeInteger;
begin
QueryPerformanceCounter(C);
Result:=C;
end;
 
 
 
 
constructor TCodeTimer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FResolution:=rsMiliSeconds;
end;
 
 
 
procedure TCodeTimer.Reset;
begin
WrkCount:=0;
TotCount:=0;
end;
 
 
procedure TCodeTimer.Start;
begin
WrkCount:=GetHiResTick;
end;
 
 
procedure TCodeTimer.Stop;
begin
TotCount:=TotCount+(GetHiResTick-WrkCount);
end;
 
procedure TCodeTimer.Display;
begin
if FResolution=rsSeconds then Caption:=FloatToStrF(TotCount/1000000,ffFixed,18,3)+' Sec.'
else Caption:=FloatToStrF(TotCount/1000,ffFixed,18,3)+' ms.'
end;
 
</syntaxhighlight>
{{out}}
<pre>
 
</pre>
 
=={{header|E}}==
Line 985 ⟶ 1,123:
println(`Counting to $count takes ${(finish-start)//1000000}ms`)
}</syntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight lang=easylang>
func fua lim .
# this is interpreted
i = 1
while i <= lim
sum += i
i += 1
.
return sum
.
start = systime
print fua 1e8
print systime - start
#
fastfunc fub lim .
# this is compiled to wasm
i = 1
while i <= lim
sum += i
i += 1
.
return sum
.
start = systime
print fub 1e8
print systime - start
</syntaxhighlight>
 
=={{header|Elena}}==
{{trans|C#}}
ELENA 46.x :
<syntaxhighlight lang="elena">import system'calendar;
import system'routines;
Line 999 ⟶ 1,166:
threadControl.sleep(1000);
new Range(0,10000).filterBy::(x => x.mod:(2) == 0).summarize();
}
Line 1,031 ⟶ 1,198:
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 46, 47, 48, 49, ...]}</syntaxhighlight>
 
=={{header|EMal}}==
{{trans|VBA}}
<syntaxhighlight lang="emal">
fun identity = int by int x
int retval = 0
for int i = 0; i < 1000; ++i
retval = x
end
return retval
end
fun sum = int by int num
int t
for int j = 0; j < 1000; ++j
t = num
for int i = 0; i < 10000; i++
t = t + i
end
end
return t
end
int startTime, finishTime
startTime = time()
identity(1)
finishTime = time()
writeLine("1000 times Identity(1) takes " + (finishTime - startTime) + " milliseconds")
startTime = time()
sum(1)
finishTime = time()
writeLine("1000 times Sum(1) takes " + (finishTime - startTime) + " milliseconds")
</syntaxhighlight>
{{out}}
<pre>
1000 times Identity(1) takes 16 milliseconds
1000 times Sum(1) takes 6160 milliseconds
</pre>
 
=={{header|Erlang}}==
Line 1,419 ⟶ 1,622:
current size: N/A 0 0 0
Note: static region values should be zero and may not be meaningful.
 
 
=={{header|Insitux}}==
Yes, non-transpiled Insitux really is this slow due to its original and ongoing commission: being shoehorned into a Roblox game.
<syntaxhighlight lang="insitux">(function measure
(let [start result end] [(time) (... . args) (time)])
(str result " took " (- end start) "ms"))
 
(function fib n
(if (< n 2) n
(+ (fib (dec n))
(fib (- n 2)))))
 
(measure fib 35)
;returns "9227465 took 26497ms"</syntaxhighlight>
 
=={{header|Ioke}}==
Line 1,429 ⟶ 1,647:
=={{header|J}}==
Time and space requirements are tested using verbs obtained through the Foreign conjunction (<code>!:</code>). <code>6!:2</code> returns time required for execution, in floating-point measurement of seconds. <code>7!:2</code> returns a measurement of space required to execute. Both receive as input a sentence for execution. The verb <code>timespacex</code> combines these and is available in the standard library.
 
<br>When the [http://www.jsoftware.com/help/dictionary/dmcapdot.htm Memoize] feature or similar techniques are used, execution time and space can both be affected by prior calculations.
There's also <code>timex</code> (which is defined as <code>6!:2</code>, but easier for some people to remember) which measures only the execution time. Interestingly, timex typically measures slightly larger times than timespacex. This is likely due to the difference between cold cache (timex) and warm cache (timespacex) -- in timespacex, the modularity of its design means that two runs of the code are performed, once to measure space use the other to measure time use.
 
When the [http://www.jsoftware.com/help/dictionary/dmcapdot.htm Memoize] feature or similar techniques are used, execution time and space can both be affected by prior calculations.
===Example===
<syntaxhighlight lang="j"> (6!:2 , 7!:2) '|: 50 50 50 $ i. 50^3' (6!:2,7!:2) '|: 50 50 50 $ i. 50^3'
0.0014169 2.09875e6
0.00488008 3.14829e6
timespacex '|: 50 50 50 $ i. 50^3'
0.0014129 2.09875e6
0.00388519 3.14829e6</syntaxhighlight>
timex '|: 50 50 50 $ i. 50^3'
0.0015032</syntaxhighlight>
 
=={{header|Janet}}==
<syntaxhighlight lang="clojure">(defmacro time
Line 1,451 ⟶ 1,675:
 
=={{header|Java}}==
If you're looking for a quick way to calculate the duration of a few lines of code you can utilize the <code>System.currentTimeMillis</code> method.
<syntaxhighlight lang="java">
long start = System.currentTimeMillis();
/* code you want to time, here */
long duration = System.currentTimeMillis() - start;
</syntaxhighlight>
<br />
{{works with|Java|1.5+}}
<syntaxhighlight lang="java">import java.lang.management.ManagementFactory;
Line 1,518 ⟶ 1,749:
console.log('test() took ' + ((end - start) / 1000) + ' seconds') // test() took 0.001 seconds
</syntaxhighlight>
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">clock
1 1023 [dup +] times pop
clock swap -.</syntaxhighlight>
 
=={{header|Julia}}==
Line 1,646 ⟶ 1,882:
 
10000 is Double (default)
 
10000&& is long long (64bit integer)
 
255ub is Byte type (unsigned value, 0 to 255)
 
Although parameter limit take the type Byte from the argument passed, the limit-limit converted to integer, so sum and n get type integer, so the loop use integers 16bit. So we use the sumtolimit2. The n-! change sign, and this cause overflow for byte value, so this removed from the sumtolimit2.
 
Function/Module Parameters in M2000 without explicitly assign type take the type from stack of values which a Read statement (which Interpreter insert to code) read from there. This type can't change for the run of module or function. We can define a parameter as variant if we want to allow changes of the type.
 
<syntaxhighlight lang="m2000 interpreter">
Line 1,652 ⟶ 1,896:
sum=limit-limit
n=sum
rem print type$(n), type$(sum), type$(limit)
n++
while limit {sum+=limit*n:limit--:n-!}
}
Module sumtolimit2 (limit) {
byte sum, n
n++
while limit {sum++:limit--}
}
Cls ' clear screen
Line 1,673 ⟶ 1,923:
Profiler
sumtolimit 10000
Print TimeCount
Profiler
sumtolimit 10000&&
Print TimeCount
Profiler
sumtolimit 255ub
Print TimeCount
Profiler
sumtolimit2 255ub
Print TimeCount
}
Checkit</syntaxhighlight>
</syntaxhighlight>
 
=={{header|Maple}}==
Line 2,149 ⟶ 2,407:
[2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]
using ''qsort()'' from [[Quicksort#Python|Quicksort]]. Timings show that the implementation of ''qsort()'' has quadratic dependence on sequence length ''N'' for already sorted sequences (instead of ''O(N*log(N))'' in average).
 
=={{header|Quackery}}==
 
<code>time</code> returns system time since Unix epoch in microseconds, but is not reliable to the microsecond, so we are using millisecond granularity. Process time is not available.
 
<syntaxhighlight lang="Quackery"> [ time ]'[ do
time swap - 1000 / ] is time: ( --> n )
 
time: [ 0 314159 times 1+ echo ]
cr cr
say "That took about " echo say " milliseconds."</syntaxhighlight>
 
{{out}}
 
<pre>314159
 
That took about 392 milliseconds.
</pre>
 
=={{header|R}}==
Line 2,321 ⟶ 2,597:
see "Elapsed time = " + elapsedTime + nl
</syntaxhighlight>
 
=={{header|RPL}}==
In its first versions, RPL did not provide user access to system clock - but advanced users knew which system call can be made on their machine to get it. The following code works on a 1987-manufactured HP-28S, but can crash on older ones and will surely do on other machines. If using a newer model, replace <code>#11CAh SYSEVAL</code> by <code>TICKS</code>, which is a (safe) built-in instruction.
{| class="wikitable"
! RPL code
! Comment
|-
|
#11CAh SYSEVAL → tick
≪ EVAL
#11CAh SYSEVAL tick -
B→R 8192 / 1 FIX RND STD
≫ ≫ '<span style="color:blue">TEVAL</span>' STO
|
<span style="color:blue">TEVAL</span> ''( ≪function≫ -- execution_time )''
Store current system time
Execute function
Measure difference in CPU cycles
convert to seconds, round to one decimal place
|}
{{in}}
<pre>
≪ 1 1000 START NEXT ≫ TEVAL
</pre>
{{out}}
<pre>
1: 6.4
</pre>
Yes, more than 6 seconds to loop 1000 times is quite slow.
 
HP-49+ models have a built-in <code>TEVAL</code> command.
 
=={{header|Ruby}}==
Line 2,480 ⟶ 2,789:
Transcript show: 2000 factorial
].</syntaxhighlight>
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "time_function" )
@( description, "Write a program which uses a timer (with the least " )
@( description, "granularity available on your system) to time how " )
@( description, "long a function takes to execute." )
@( see_also, "http://rosettacode.org/wiki/Time_a_function" );
pragma annotate( author, "Ken O. Burtch" );
pragma license( unrestricted );
 
pragma restriction( no_external_commands );
 
procedure time_function is
 
procedure sample_function( num : in out integer ) is
begin
for i in 1..1000 loop
num := @+1;
end loop;
end sample_function;
 
start_time : calendar.time;
end_time : calendar.time;
seconds : duration;
 
procedure time_sample_function is
sample_param : integer := 4;
begin
start_time := calendar.clock;
sample_function( sample_param );
end_time := calendar.clock;
seconds := end_time - start_time;
end time_sample_function;
 
begin
time_sample_function;
put_line( "sum(4) takes:" & strings.image( seconds ) & " seconds." );
command_line.set_exit_status( 0 );
end time_function;</syntaxhighlight>
 
=={{header|Standard ML}}==
Line 2,729 ⟶ 3,079:
{{libheader|Wren-check}}
The only way Wren currently has to time a function (encapsulated in the ''Benchmark.run'' method) is to measure the System time before and after the function is called. We therefore use that approach, averaging over say 100 runs, having first shut down as many other processes as we can.
<syntaxhighlight lang="ecmascriptwren">import "./check" for Benchmark
 
Benchmark.run("a function", 100, true) {
Line 2,795 ⟶ 3,145:
{{out}}
<pre>3</pre>
 
=={{header|ZX Spectrum Basic}}==
The ZX Spectrum has very little in the way of timing functionality; its best clock is the three-byte FRAMES variable, which starts at zero when the system is turned on and updates every time the ULA refreshes the screen, giving a granularity of one fiftieth of a second. As the system cannot multitask, a difference between the start and end time is as good as we can get; certain actions, most notably operating the system BEEPer, temporarily stop the counter.
 
<syntaxhighlight lang="zxbasic">
1 DEF FN t()=(PEEK 23672+256*PEEK 23673+65536*PEEK 23674)/50
10 LET time=FN t()
20 PRINT ASN 0.5
30 PRINT FN t()-time</syntaxhighlight>
{{out}}
<pre>0.52359878
0.22
 
0 OK, 30:1</pre>
9,482

edits