High Resolution Timer Search

In C ++ for Linux, I try to do something every microseconds / nanoseconds, and currently I use the nanolex function below. It works, however, if the code is repeated millions of times, it becomes expensive. I am looking for a timer with a high resolution that will allow a very accurate time (application - 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); } 
+5
source share
3 answers

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 the -std=c++11 flag.

+4
source

For audio / video, as a rule, you do not need nano / micro seconds accuracy timers, milliseconds are enough. The most common packet spacing in audio is 20 ms. For this purpose, you need to use nanosleep.

In addition, if you are not using a real-time OS, you cannot guarantee that you get such good timings from the kernel.

Pitfall real-time sleep usage: they do not support the corresponding frequency (50 Hz for sound at 20 ms intervals). Because at each tick, you add processing time to the wait interval. Thus, the wait interval should be calculated based on the previous tick timestamp and the next expected timestamp.

You can implement a short intermediate timer (for example, 10 ms) with sleep modes and process events that should occur between these timer alarms when the timer is triggered. If you do this, you optimize the use of OS resources (minimizing process / thread context switching).

+1
source

You can get permission for a microsecond using getitimer (2):

http://man7.org/linux/man-pages/man2/setitimer.2.html

0
source

All Articles