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!
What about good old alarms and signals?
#include <unistd.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;
}
EDIT: the boilerplate code above does not allow you to print any of the internal state, however since you are using C++14 you can simply capture that in a closure, and then use the closure to dig into the internals, like
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <iostream>
#include <functional>
using namespace std;
std::function<void()> myClosure; // The closure needs to be accessible to the alarm-function
void catchAlarm(int sig) {
myClosure();
exit(-1);
}
int main(){
int c=0;
myClosure = [&]()->void{
std::cerr << "You will now die at age " << c << "\n";
};
// 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;
}
However (and this may be a big however or small one depending on your case), signals are triggered by the kernel, and it may execute at any time, including while half way through code which the compiler was executing sequentially, but now are not as your alarm interrupted it halfway though. In your case where your just print stuff, you may be fine as worst case would be some funny output, but if your lambda is modifying any object you may end up with problems that resemble that of non-thread safe code.