Measuring elapsed time, storing the start time as a primitive type

Viewed 227
  1. I need to measured elapsed time in ms

  2. I need to store the start time as a primitive type

  3. I need to retrieve the start time as a primitive type, when making the comparison to determine how much time has elapsed

Any suggestions?

I have C++17 and do not want to use any external libraries (like boost).

std::chrono would be fine if someone could explain to me how to convert the elapsed time to/from a primitive. I'm not very good at C++.

resolution accuracy is not important.. if it is off by tens of ms that's ok, I just need to implement a delay.. e.g. 100ms or 1.5s

2 Answers

Because you are storing the start time, you should use std::chrono::system_clock. Its epoch is stable, and will not change with time. Other std::chrono clocks have an epoch that may change between runs of a program, and thus time points stored by one run and read back in by a subsequent run may not be consistent.

To get the current time in milliseconds:

auto now = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());

I like to use either a using directive or a namespace alias to make such code less verbose:

using namespace std::chrono;
auto now = time_point_cast<milliseconds>(system_clock::now());

To convert now into a signed 64 bit integral type:

auto now_i = now.time_since_epoch().count();

To convert now_i back into a time_point:

time_point<system_clock, milliseconds> prev{milliseconds{now_i}};

To compare time_points:

if (now > prev)
    ...

Everything above is in the header <chrono>:

#include <chrono>

You can simply do this by:

double time = 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC;

See the below code for better understanding.

#include <iostream>
#include <time.h>

using namespace std;

int main() {
  double start = 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC;

  for(int i=0;i<1e9;i++);

  double end = 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC;

  double time_taken = end - start;
  cout << time_taken << "ms\n";
  
  return 0;
}

Include the header file:

#include <time.h> // include this
Related