Logo

Programming-Idioms

  • C++
  • Go

Idiom #125 Measure function call duration

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

import "time"
t1 := time.Now()
foo()
t := time.Since(t1)
ns := t.Nanoseconds()
fmt.Printf("%dns\n", ns)

t1 has type time.Time.
t has type time.Duration.
ns has type int64.
import "time"
t1 := time.Now()
foo()
t := time.Since(t1)
ns := int64(t / time.Nanosecond)
fmt.Printf("%dns\n", ns)

t1 has type time.Time.
t has type time.Duration.
#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();

c++ 11
(time (foo))

time prints time elapsed, but in ms

New implementation...
< >
JPSII