Programming-Idioms

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.

import time
start = time.time()
f()
end = time.time()
return end - start
import timeit
duration = timeit.timeit("f()", setup="from __main__ import f")
#include <ctime>
std::clock_t start = std::clock();
f();
double duration = (std::clock() - start) / (double) CLOCKS_PER_SEC;
using System.Diagnostics;
var sw=new Stopwatch();
sw.Start();
f();
sw.Stop();
var duration=sw.Elapsed;

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;
  integer, parameter :: i8 = selected_int_kind(15)
  integer(kind=i8) :: start, finish, rate

  call system_clock (count_rate=rate)
  call system_clock (count=start)
  call f()
  call system_clock (count=finish)
  print *,(finish-start)/real(rate)
import "time"
func clock(f func()) time.Duration {
	t := time.Now()
	f()
	return time.Since(t)
}
function clock(f) {
  var start = new Date().getTime();
  f();
  var end = new Date().getTime();
  return end - start;
}
long clock(Runnable f) {
    long t0 = System.currentTimeMillis();
    f.run();
    long t1 = System.currentTimeMillis();
    return t1 - t0;
}
$start = microtime(TRUE);
f();
$end = microtime(TRUE);
echo $end - $start, PHP_EOL;
var
  Start, Duration: TDateTime;
begin
  Start := Now;
  f;
  Duration := Now - Start;
end.
use Benchmark qw(:hireswallclock timediff timestr);
sub f {};
my $start = Benchmark->new;
f;
print timestr timediff(Benchmark->new, $start);
def clock 
  t = Time.now
  yield
  Time.now - t
end

clock{ f }
use std::time::Instant;
let start = Instant:now();
f();
let duration = start.elapsed();

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

Idiom created by

programming-idioms.org

Related idioms