I've been researching on it for quite a while but still don't know how to do it. #include<chrono> seemed to be the answer at one point but then I realized I can't use it in visual studio 2010. I also researched on <ctime> but all I found is on how to make timers for timing the length of a program and basic timers in general.
I would appreciate it very much if someone could show me the general format for running a program or function in a specified time period.
#include <unistd.h>
#include <ctime>
#include <iostream>
usingnamespace std;
int main(int argc, char *argv[])
{
constlong timeout = 10;
long elapsed_seconds = 0;
bool time_up = false;
timespec ts_start;
clock_gettime(CLOCK_MONOTONIC, &ts_start); // get the program start time
while (!time_up)
{
sleep(1); //some arbitrary stuff, representing the work you want to do in your program
timespec ts_curr;
clock_gettime(CLOCK_MONOTONIC, &ts_curr); // get current time
elapsed_seconds = ts_curr.tv_sec - ts_start.tv_sec;
cout << argv[0] << " has been running for " << elapsed_seconds << " seconds." << endl;
// food for thought - what if (elapsed_seconds < 0) ?? :-)
if (elapsed_seconds >= timeout)
{
time_up = true;
}
}
cout << endl << argv[0] << " ran for " << elapsed_seconds << " seconds." << endl;
}