Programming-Idioms

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

Idiom #125 Measure function call duration

measure the duration t, in nano seconds, of a call to the function foo. Print this duration.

(time (foo))
#include <chrono>
auto start = std::chrono::steady_clock::now();
foo();
auto end = std::chrono::steady_clock::now();
auto t = std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count();
import std.datetime;
StopWatch sw;
sw.start;
foo;
auto t = sw.peek.nsecs; 
writeln(t);
  integer, parameter :: i8 = selected_int_kind(15)
  integer (kind=i8) :: count, count_rate, count_2
  x = 1.2
  call system_clock (count, count_rate)
  call f
  call system_clock (count_2)
  if (count_rate == 10**9) then
    print *,"The call to f used ", (count_2-count), "Nanoseconds"
  else
    print *,"The call to f used ", (count_2-count)/real(count_rate)*1e9, "Nanoseconds"
  end if
import "time"
t1 := time.Now()
foo()
t := time.Since(t1)
ns := t.Nanoseconds()
fmt.Printf("%dns\n", ns)
import "time"
t1 := time.Now()
foo()
t := time.Since(t1)
ns := int64(t / time.Nanosecond)
fmt.Printf("%dns\n", ns)
console.time('foo');
foo();
console.timeEnd('foo');
(time (foo))
uses sysutils;
var
  t1, t: QWord;
begin
  t1 := GetTickCount64;
  foo;
  t := (GetTickCount64 - t1) * 1000000;
  writeln(t);
end.
use Benchmark qw(:hireswallclock timediff);
sub foo {};
my $start = Benchmark->new;
foo;
my $t = timediff(Benchmark->new, $start)->[0] * 10**9; 
import time
t1 = time.perf_counter()
foo()
t2 = time.perf_counter()
print('Seconds:', t2 - t1)
t1 = Time.now
foo
p (Time.now - t1)*1000000
use std::time::{Duration, Instant};
let start = Instant::now();
foo();
let duration = start.elapsed();
println!("{}", duration);

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

Idiom created by

JPSII

Related idioms