In C++ for Linux, I am trying to do something every microsecond/nanosecond and am currently using the nanosleep function below. It works, however if the code loops millions of times, this becomes expensive. I'm looking for a high resolution timer that will allow for a very precise timing (the application is audio/video). Any ideas?
struct timespec req = {0};
req.tv_sec = 0;
req.tv_nsec = 1000000000L / value;
for(long i = 0; i < done; i++)
{
printf("Hello world");
nanosleep(&req, (struct timespec *)NULL);
}
Using C++11
#include <chrono>
#include <thread>
...
for (long i = 0; i < done; i++) {
std::cout << "Hello world" << std::endl;
std::this_thread::sleep_for(std::chrono::nanoseconds(1e9 / value));
}
Remember to compile with -std=c++11
flag.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With