C/C++ time_t in microseconds

Strife picture Strife · Jun 15, 2015 · Viewed 12.8k times · Source

This program returns the time in seconds. I need to return it in microseconds.

time_t timeStart = time(0);
usleep(2.5e6);
time_t timeEnd = time(0);

float R = (timeEnd - timeStart);
std::cout << R << std::endl;

Answer

Lukas W picture Lukas W · Jun 15, 2015

If you're looking for a higher resolution, you can use std::chrono::high_resolution_clock from C++11.

#include <chrono>

using namespace std::chrono;

high_resolution_clock::time_point t1 = high_resolution_clock::now();

/* some extensive action... */
usleep(2.5e6);

high_resolution_clock::time_point t2 = high_resolution_clock::now();

duration<double> time_span = duration_cast<duration<double>>(t2 - t1);

std::cout << "It took me " << time_span.count() << " seconds.";
std::cout << std::endl;

Outputs something like

It took me 0.091001 seconds.

Example from http://www.cplusplus.com/reference/chrono/high_resolution_clock/now/