Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for a high resolution timer

Tags:

c++

linux

timer

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);
}
like image 287
Josh Avatar asked Jul 10 '15 04:07

Josh


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

like image 181
Shreevardhan Avatar answered Sep 24 '22 22:09

Shreevardhan