超时太常用了, 下面来写一个进程计时器, 并用它来做超时限制

#include <windows.h>
#include <ctime>
#include <iostream>
using namespace std;

//  计时器
long getTime()
{
	static int flag = 1;
	static long firstTime = 0;
	
	if(1 == flag)
	{
		firstTime = time(NULL);
		flag = -1;

		return 0; // 第一次调用的时间设置0
	}

	return time(NULL) - firstTime; // 相对于第一次的秒数
}

int main()
{
	long t1 = getTime();
	cout << t1 << endl;

	Sleep(3000);

	long t2 = getTime();
	cout << t2 << endl;

	while(getTime() - t2 < 10) // 10s 超时时间内
	{
		cout << "hello world" << endl;
		Sleep(1000);
	}

	return 0;
}



本文转载:CSDN博客