Snehasish Karmakar Snehasish Karmakar - 6 months ago 16
Bash Question

set execution time of a c++ code beforehand

I want a C++ code to run for a specific amount of time and complete a statement before ending the execution. For example, consider the following scenario regarding the execution of a program:


Initialise a counter with 0. If the execution time is equal to x milliseconds then print the current value of the counter, else increment the counter by 1.


The above task might be accomplished by writing a C++ code something like:

#include<iostream>
using namespace std;

int main(){
int c=0;
while(true){
/* do something to check the execution time,
if it is equal to x milliseconds print the value of c and exit*/

c++;
}
return 0;
}


Actually, I want to compare two optimization algorithms implemented in C++ for a particular problem based on how much optimal solution they can give if executed for the same amount of time.

I searched on the Internet, but could not get what I actually want. It looks like thread based solutions are there, but I don't want threads to be involved unless it is extremely necessary. It is favourable if the problem can be solved by some C++ features alone, but it is okay if some shell script to invoke the C++ code would do the trick (I am likely to run the codes on Linux system). Any help is appreciated!

Answer

What about good old alarms and signals?

#include <alarm.h>
#include<iostream>
using namespace std;

void catchAlarm(int sig) {
    std::cerr << "You will now die, Mr Bond!!\n";
    exit(-1);
}

int main(){
    int c=0;

    // Die in 2 seconds....
    signal(SIGALRM, catchAlarm);
    alarm(2); 

    while(true){
        /* do something to check the execution time, 
        if it is equal to x milliseconds print the value of c and exit*/

        c++;
    }
    return 0;
}