Reputation: 4125
I am trying to create a timer to profile some functions. For example,
#include <date_time/posix_time/posix_time.hpp>
boost::posix_time::ptime t1, t2;
t1 = boost::posix_time::microsec_clock::local_time();
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
t2 = boost::posix_time::microsec_clock::local_time();
std::cout << to_simple_string(t1) << std::endl;
std::cout << to_simple_string(t2) << std::endl;
The output I get is this,
2012-Mar-04 08:21:24.760019
2012-Mar-04 08:21:25.760577
The actual time elapsed is 1 second and 558 micro second, is there anyway that I can improve this accuracy to say under 1 microsecond?
I also tried something like this, with linker -lrt.
#include <time.h>
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &timer_start);
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
clock_gettime(1CLOCK_PROCESS_CPUTIME_ID, &timer_end);
But the compiler returns a semantic error for CLOCK_PROCESS_CPUTIME_ID. The error message is as follow.
Description Resource Path Location Type
Symbol 'CLOCK_PROCESS_CPUTIME_ID' could not be resolved _OVERVIEW.cpp /FUTETP/BACKEND line 32 Semantic Error
Upvotes: 1
Views: 1804
Reputation: 4953
Please keep in mind two things:
sleep()
and other time-sensitive commands could be inaccurate for several reasons (system load, etc.). You will never get within 1 microsecond accuracy. 500 microseconds isn't too bad for timing sleep()
By the way, I'm unsure of what method Boost is using to get the time, but consider gettimeofday(2)
from sys/time.h
(or newer clock_gettime()
from time.h
). It returns the time since midnight Jan 1, 1970. Record the time before and after and subtract. Here's an example of gettimeofday()
.
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
unsigned int
timeDif(
struct timeval *before,
struct timeval *after)
{
return ((after->tv_sec * 1000000 + after->tv_usec) -
(before->tv_sec * 1000000 + before->tv_usec));
}
int
main(
int argc,
char *argv[]) {
struct timeval before, after;
gettimeofday(&before, NULL);
sleep(1);
gettimeofday(&after, NULL);
printf("Elapsed time: %u microseconds\n", timeDif(&before, &after));
return (0);
}
Upvotes: 1