user1185853
user1185853

Reputation: 49

c++ timer linux

I need to know how create a timer or measure out 500ms in C++ in a linux environment. I have tried using gettimeofday and using the time structure but cant get the correct precision for milliseconds. What I am trying to do is have an operation continue for a max of 500ms...after 500ms something else happens.

Upvotes: 0

Views: 5485

Answers (4)

bames53
bames53

Reputation: 88155

#include <chrono>
#include <iostream>
#include <future>
#include <atomic>

void keep_busy(std::chrono::milliseconds this_long,std::atomic<bool> *canceled) {
    auto start = std::chrono::high_resolution_clock::now();
    while(std::chrono::high_resolution_clock::now() < start+this_long) {
        std::cout << "work\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
        if(canceled->load()) {
            std::cout << "canceling op\n";
            throw "operation canceled";
        }
    }
}

int main() {
    std::atomic<bool> canceled(false);
    auto future = std::async(std::launch::async,
        keep_busy,std::chrono::milliseconds(600),&canceled);
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    canceled.store(true);
    try {
        future.get();
        std::cout << "operation succeded\n";
    } catch( char const *e) {
        std::cout << "operation failed due to: " << e << '\n';
    }
}

I'm not entirely sure this is correct...

Upvotes: 0

YankeeWhiskey
YankeeWhiskey

Reputation: 1582

Since you are in Linux, you can use the system call usleep

   int usleep(useconds_t usec);

Which will let your process sleep for some microseconds period.

Upvotes: 1

111111
111111

Reputation: 16148

If you have access to C++11 then your best bet it to use std::chrono library

http://en.cppreference.com/w/cpp/chrono/duration

I aren't entirely sure what you want to do with it do you want to wait for exactly 500ms?

you can so this for that

std::this_thread::sleep_for(std::chrono::milliseconds(500));

you can do an operation until 500 milliseconds has elapsed by getting a time pointer and check to see whether timepoint - system_time::now() is greater than 500ms

//if you compiler supports it you can use auto
std::chrono::system_clock::time_point start=std::chrono::system_clock::now();

while(start-std::chrono::system_clock::now() 
          < std::chrono::milliseconds(500))
{
    //do action
}

If you don't have C++11 this will also work with boost chrono library. The advantage of this approach is that it is portable unlike using linux time functions.

Upvotes: 3

jjlin
jjlin

Reputation: 4703

Your question isn't really clear about why you "can't get the correct precision" or what happens when you try to do that, but if you're having trouble with gettimeofday, consider using clock_gettime instead. man clock_gettime for details.

Upvotes: 1

Related Questions