Reputation: 675
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);
}
Upvotes: 5
Views: 934
Reputation: 3825
For audio/video typically you don't need nano/micro seconds precision timers, milliseconds is enough. The most common inter-packet interval in audio is 20ms. It is okey to use nanosleep for that purpose.
Moreover unless you use realtime OS you can't guarantee to get so good timings from the kernel.
Pitfall of using sleeps in realtime communications is: they don't keep appropriate frequency (50Hz for audio with 20ms interval). Because on each tick you add processing time to sleep interval. So sleep interval must be calculated based on previous tick timestamp and next expected tick timestamp.
You can implement short interval timer (10ms for example) with sleeps and process events that should occur between this timer alarms on timer alarms. If you do so you will optimise OS resource usage (minimising process/threads context switching).
Upvotes: 1
Reputation: 12641
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.
Upvotes: 4
Reputation: 885
You can get microsecond resolution with getitimer(2):
http://man7.org/linux/man-pages/man2/setitimer.2.html
Upvotes: 0