Logo

Programming-Idioms

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

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
#include <ctime>
std::clock_t start = std::clock();
f();
double duration = (std::clock() - start) / (double) CLOCKS_PER_SEC;
#include <chrono>

double measure() {
    using namespace std::chrono;
    const auto start{ high_resolution_clock::now() };
    f();
    const auto elapsed{ high_resolution_clock::now() - start };
    const double seconds{ duration_cast<duration<double>>(elapsed).count() };
    return seconds;
}
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;
var s = Stopwatch()..start();
f();
s.stop();
print(s.elapsed);
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);
import time
start = time.time()
f()
end = time.time()
return end - start
import timeit
duration = timeit.timeit("f()", setup="from __main__ import f")
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();