Home > Back-end >  Time taken between two points in code independent of system clock CPP Linux
Time taken between two points in code independent of system clock CPP Linux

Time:11-08

I need to find the time taken to execute a piece of code, and the method should be independent of system time, ie chrono and all wouldn't work.

My usecse looks somewhat like this.

int main{
   //start
   function();
   //end
   time_take = end - start;
}

I am working in an embedded platform that doesn't have the right time at the start-up. In my case, the start of funcion happens before actual time is set from ntp server and end happens after the exact time is obtained. So any method that compares the time difference between two points wouldn't work. Also, number of CPU ticks wouldn't work for me since my programme necessarily be running actively throughout.

I tried the conventional methods and they didn't work for me.

CodePudding user response:

On Linux clock_gettime() has an option to return the the current CLOCK_MONOTONIC, which is unaffected by system time changes. Measuring the CLOCK_MONOTONIC at the beginning and the end, and then doing your own math to subtract the two values, will measure the elapsed time ignoring any system time changes.

CodePudding user response:

If you don't want to dip down to C-level abstractions, <chrono> has this covered for you with steady_clock:

int main{
   //start
   auto t0 = std::chrono::steady_clock::now();
   function();
   auto t1 = std::chrono::steady_clock::now();
   //end
   auto time_take = end - start;
}

steady_clock is generally a wrapper around clock_gettime used with CLOCK_MONOTONIC except is portable across all platforms. I.e. some platforms don't have clock_gettime, but do have an API for getting a monotonic clock time.

Above the type of take_time will be steady_clock::duration. On all platforms I'm aware of, this type is an alias for nanoseconds. If you want an integral count of nanoseconds you can:

using namespace std::literals;
int64_t i = time_take/1ns;

The above works on all platforms, even if steady_clock::duration is not nanoseconds.

The minor advantage of <chrono> over a C-level API is that you don't have to deal with computing timespec subtraction manually. And of course it is portable.

  • Related