0

I am using c++ and want to create a method, that terminates after a given timespan (e.g. 50microseconds) like a contract algorithm.

The method is using loops so my idea was to use the std::chrono::high_resolution_clock::now() method to measure elapsed time.

Unfortunately this is not very fast and the method runs way slower than the initial one.

What is the best / a better way to archieve the same result?

How do other contract / anytime algorithms handle this problem?

lapayo
  • 97
  • 1
  • 8

2 Answers2

1

Have you considered using a timer interrupt? This way you would avoid having to poll; it instead leverages hardware native to your systems clock to alert your CPU when 50 ms have passed. Without knowing the exact structure of your loop it may look something like this:

#include <sys/time.h>

bool flag;
void handler(int signum){
    flag = true;
}


int main (){
    struct sigaction s_action;
    struct itimerval timer;

    memset (&s_action, 0, sizeof (s_action));
    s_action.sa_handler = &handler;
    sigaction (SIGVTALRM, &s_action, NULL);


    timer.it_value.tv_sec = 0;
    timer.it_value.tv_usec = 50000;         // 50 ms until next signal
    timer.it_interval.tv_sec = 0;
    timer.it_interval.tv_usec = 50000;      // 50 ms between signals

    setitemer(ITIMER_VIRTUAL, &timer, NULL);

    flag = false;
    while(true){
        if(flag)
            break;
        /* do stuff */
    }
}
0

What I would have done is:

Have a monitor thread. Monitor thread spawns the worker thread. Monitors thread has the waiting loop, but not the busy waiting loop. Use yield which is << total time allowed for child thread.

If child is running more than the contract time, kill child thread.

Downside of the algo. Needs clever handling clean up function for the killed thread, so that it does not leave you in unhappy state if child needs to be killed.

We can use similar idea if thinking in terms of processes, instead of threads.

Ritesh
  • 1,809
  • 1
  • 14
  • 16
  • I tested this approach, but this lead to new problems. Instead of having slower processing, I get very slow start, even with a threadpool it took 13.000 - 50.000ns to even start running my task on an idle quadcore i5. Since I wanted to terminate the task after 50.000ns, I often havent even got a single calculation done when killing the task. – lapayo May 20 '16 at 12:39