How to make a program or function run within a specified time period?

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.
Not sure what you mean, my interpretation of the question seems to simplistic to be correct.

However, if you just want to kick off a program and have it run for x seconds, you have several options.

Create a timer and register a signal handler that handles it's expiration by terminating the program.

Create a secondary thread that sleeps for the required period and then wakes up to terminates the program

Condition variable...

Have an infinite loop in main that checks the time (or a timer status) every pass through the loop and terminates when time runs out

Okay, I said the problem is unclear, so don't call me silly
Yes, your interpretation is correct.

I just need a kind of structure for the code so I can get started on something.
A bare-bones do-little example then:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <unistd.h>
#include <ctime>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
	const long 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;
}
Topic archived. No new replies allowed.