Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take time in milliseconds

Tags:

c++

I have found the usleep function in unistd.h, and I thought it was useful to wait some time before every action.But I have discovered that the thread just sleeps if it it doesn't receive any signal.For example if I press a button (I'm using OpenGL but the question is more specific about time.h and unistd.h), the thread gets awaken and I'm not getting what I want. In time.h there is the sleep function that accepts an integer but an integer is too much ( I want to wait 0.3 seconds), so I use usleep. I ask if there is a function to take time in milliseconds (from any GNU or whatever library). It should work like time(), but returning milliseconds instead of seconds.Is that possibile?

like image 481
Ramy Al Zuhouri Avatar asked Dec 10 '22 01:12

Ramy Al Zuhouri


1 Answers

If you have boost you can do it this way:

#include <boost/thread.hpp>

int main()
{
  boost::this_thread::sleep(boost::posix_time::millisec(2000));
  return 0;
}

This simple example, as you can see in the code, sleeps for 2000ms.

Edit:

Ok, I thought I understood the question but then I read the comments and now I'm not so sure anymore.

Perhaps you want to get how many milliseconds that has passed since some point/event? If that is the case then you could do something like:

#include <boost/chrono.hpp>
#include <boost/thread.hpp>
#include <iostream>


int main()
{
  boost::chrono::high_resolution_clock::time_point start = boost::chrono::high_resolution_clock::now();
  boost::this_thread::sleep(boost::posix_time::millisec(2000));
  boost::chrono::milliseconds ms = boost::chrono::duration_cast<boost::chrono::milliseconds> (boost::chrono::high_resolution_clock::now() - start);
  std::cout << "2000ms sleep took " << ms.count() << "ms " << "\n";
  return 0;
}

(Please excuse the long lines)

like image 68
mantler Avatar answered Dec 24 '22 05:12

mantler