Time a function: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(add RPL)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(16 intermediate revisions by 10 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,457 ⟶ 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,657 ⟶ 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,663 ⟶ 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,684 ⟶ 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,160 ⟶ 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,334 ⟶ 2,599:
 
=={{header|RPL}}==
In its first versions, RPL did not provide user access to system clock - but advacancedadvanced users knowknew 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 on other machines. If using a newer model, replace <code>#11CAh SYSEVAL</code> by <code>TICKS</code>, which is a (safe) built-in instruction.
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
Line 2,346 ⟶ 2,610:
#11CAh SYSEVAL tick -
B→R 8192 / 1 FIX RND STD
≫ ≫ '<span style="color:blue">TEVAL</span>''TIMER'''’ STO
|
'''TIMER'''<span style="color:blue">TEVAL</span> ''( ≪function≫ -- execution_time )''
Store current system time
Execute function
Line 2,357 ⟶ 2,621:
{{in}}
<pre>
≪ 1 1000 START NEXT ≫ TIMERTEVAL
</pre>
{{out}}
Line 2,363 ⟶ 2,627:
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}}==
Ruby's Benchmark module provides a way to generate nice reports (numbers are in seconds):
Line 2,812 ⟶ 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) {
9,479

edits