Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ time_t in microseconds

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;
like image 886
Strife Avatar asked Apr 27 '26 07:04

Strife


1 Answers

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/

like image 96
Lukas W Avatar answered Apr 28 '26 21:04

Lukas W