Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current time in milliseconds using C++ and Boost

In my thread (using boost::thread) I need to retrieve the current time in ms or less and to convert into ms:

Actually, reading here I've found this:

tick = boost::posix_time::second_clock::local_time(); now  = boost::posix_time::second_clock::local_time(); 

And seems to work, but after I need to have a long value of the milliseconds of the now...

How can I do it?

like image 221
ghiboz Avatar asked Jul 18 '11 14:07

ghiboz


2 Answers

You can use boost::posix_time::time_duration to get the time range. E.g like this

boost::posix_time::time_duration diff = tick - now; diff.total_milliseconds(); 

And to get a higher resolution you can change the clock you are using. For example to the boost::posix_time::microsec_clock, though this can be OS dependent. On Windows, for example, boost::posix_time::microsecond_clock has milisecond resolution, not microsecond.

An example which is a little dependent on the hardware.

int main(int argc, char* argv[]) {     boost::posix_time::ptime t1 = boost::posix_time::second_clock::local_time();     boost::this_thread::sleep(boost::posix_time::millisec(500));     boost::posix_time::ptime t2 = boost::posix_time::second_clock::local_time();     boost::posix_time::time_duration diff = t2 - t1;     std::cout << diff.total_milliseconds() << std::endl;      boost::posix_time::ptime mst1 = boost::posix_time::microsec_clock::local_time();     boost::this_thread::sleep(boost::posix_time::millisec(500));     boost::posix_time::ptime mst2 = boost::posix_time::microsec_clock::local_time();     boost::posix_time::time_duration msdiff = mst2 - mst1;     std::cout << msdiff.total_milliseconds() << std::endl;     return 0; } 

On my win7 machine. The first out is either 0 or 1000. Second resolution. The second one is nearly always 500, because of the higher resolution of the clock. I hope that help a little.

like image 50
mkaes Avatar answered Oct 05 '22 09:10

mkaes


If you mean milliseconds since epoch you could do

ptime time_t_epoch(date(1970,1,1));  ptime now = microsec_clock::local_time(); time_duration diff = now - time_t_epoch; x = diff.total_milliseconds(); 

However, it's not particularly clear what you're after.

Have a look at the example in the documentation for DateTime at Boost Date Time

like image 20
Brian O'Kennedy Avatar answered Oct 05 '22 08:10

Brian O'Kennedy