Time a function: Difference between revisions

added ocaml
(add Common Lisp example)
(added ocaml)
Line 44:
 
=={{header|C++}}==
<cpp>#include <ctime>
#include <iostream>
using namespace std;
 
int identity(int x) { return x; }
int sum(int num) {
for (int i = 0; i < 1000000; i++)
num += i;
return num;
}
 
double time_it(int (*action)(int), int arg) {
clock_t start_time = clock();
action(arg);
clock_t finis_time = clock();
return ((double) (finis_time - start_time)) / CLOCKS_PER_SEC;
}
 
int main() {
cout << "Identity(4) takes " << time_it(identity, 4) << " seconds." << endl;
cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl;
return 0;
}</cpp>
}
 
===Example===
Line 108:
(6!:2,7!:2) '|: 50 50 50 $ i. 50^3'
0.00387912 1.57414e6
 
=={{header|OCaml}}==
<ocaml>let time_it action arg =
let start_time = Sys.time () in
ignore (action arg);
let finish_time = Sys.time () in
finish_time -. start_time</ocaml>
 
===Example===
# Printf.printf "Identity(4) takes %f seconds.\n" (time_it (fun x -> x) 4);;
Identity(4) takes 0.000000 seconds.
- : unit = ()
# let sum x = let num = ref x in for i = 0 to 999999 do num := !num + i done; !num;;
val sum : int -> int = <fun>
# Printf.printf "Sum(4) takes %f seconds.\n" (time_it sum 4);;
Sum(4) takes 0.084005 seconds.
- : unit = ()
 
=={{header|Python}}==
Line 113 ⟶ 130:
 
'''Note:''' There is an overhead in executing a function that does nothing.
<python>import sys, timeit
def usec(function, arguments):
modname, funcname = __name__, function.__name__
timer = timeit.Timer(stmt='%(funcname)s(*args)' % vars(),
setup='from %(modname)s import %(funcname)s; args=%(arguments)r' % vars())
try:
t, N = 0, 1
while t < 0.2:
t = min(timer.repeat(repeat=3, number=N))
N *= 10
microseconds = round(10000000 * t / N, 1) # per loop
return microseconds
except:
timer.print_exc(file=sys.stderr)
raise
 
def nothing(): pass
def identity(x): return x</python>
 
===Example===
>>> print usec(nothing, [])
Anonymous user