How to get execution time of a piece of code in C++?

benchmarking, c++, execution-time, linux

Solution

If available on your OS you can use the times API to get similar results as the built in `time` command.

#include <sys/times.h>
...
struct tms  start, end;
times(&start);
//Do command
times(&end);
clock_t usr_time = end->tms_utime - start->tms_utime;
clock_t sys_time = end->tms_stime - start->tms_stime;

To be 100% complete you should check that the result of times is not equal to `-1` and check the `errno` code otherwise.

Problem

I'm trying to benchmark a piece of code. It is based on this code here with the interesting part basically looking like this: ``` auto t0 = std::chrono::high_resolution_clock::now(); ... auto t1 = std::chrono::high_resolution_clock::now(); std::cout << secs(t1-t0).count() << " s\n"; ``` The problem is that I am on a shared machine, and this is giving me wall time, so my results are not giving me anything consistent. What I really need is some sort of stopwatch tool that will allow me get just the time in which my code is running, rather than the wall time. What options are there? I'm on a Linux machine if it comes to system specific calls, but I'd rather keep this code portable if possible. I've looked at other questions such as this and this but they all seem to offer wall time solutions.

Original source

Related problems