Reputation: 39
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;
Upvotes: 2
Views: 17479
Reputation: 172
using function gettimeofday
#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv, const struct timezone *tz);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
settimeofday(): _BSD_SOURCE
Description
The functions gettimeofday()
and settimeofday()
can get and set the time as well as a timezone. The tv argument is a
struct timeval
(as specified in ):
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
and gives the number of seconds and microseconds since the Epoch (see time(2)). The tz argument is a struct timezone
:
struct timezone {
int tz_minuteswest; /* minutes west of Greenwich */
int tz_dsttime; /* type of DST correction */
};
this function can get microsecond
Upvotes: 3
Reputation: 305
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/
Upvotes: 6
Reputation: 4245
Take a look at the std::chrono
header. It contains many different options for time manipulation, including the ability to convert to microseconds
via std::chrono::duration_cast
.
Upvotes: 2