This language bar is your friend. Select your favorite languages!

Idiom #132 Measure duration of procedure execution

Run procedure f, and return the duration of the execution of f.

function clock(f) {
  var start = new Date().getTime();
  f();
  var end = new Date().getTime();
  return end - start;
}
#include <ctime>
std::clock_t start = std::clock();
f();
double duration = (std::clock() - start) / (double) CLOCKS_PER_SEC;
import std.datetime;
auto elapsed = benchmark!f(1)[0].msecs;
import std.datetime;
{
    import std.stdio;
    auto mt = measureTime!((TickDuration a{writeln(a.msecs);});
    f();
}
import std.datetime;
StopWatch sw;
sw.start;
f();
auto elapsed = sw.peek;
import "time"
func clock(f func()) time.Duration {
	t := time.Now()
	f()
	return time.Since(t)
}
long clock(Runnable f) {
    long t0 = System.currentTimeMillis();
    f.run();
    long t1 = System.currentTimeMillis();
    return t1 - t0;
}
var
  Start, Duration: TDateTime;
begin
  Start := Now;
  f;
  Duration := Now - Start;
end.
import timeit
duration = timeit.timeit("f()", setup="from __main__ import f")
def clock 
  t = Time.now
  yield
  Time.now - t
end

clock{ f }

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms