我是靠谱客的博主 单薄西牛,这篇文章主要介绍C++设置一个函数的运行时间,如果超时,就跳过该函数,现在分享给大家,希望可以做个参考。

#include<Windows.h>
#include<iostream>
#include<tchar.h>
#include<string>
#include<ctime>
using namespace std;
struct mytime//定义一个传入函数的结构体
{
int t1;
int t2;
};
DWORD WINAPI f1(LPVOID lpParameter)//定义一个需要运行的函数
{
mytime* t = (mytime*)lpParameter;
cout << t->t1 << "
" << t->t2 << endl;
Sleep(t->t1 + t->t2);
return 0;
}
int main()
{
clock_t start_time = clock();
mytime T = { 3000,5000 };
HANDLE hThread1;
hThread1 = CreateThread(NULL, 0, f1, &T, 0, NULL);//运行f1函数,并传入结构体参数
int signal=WaitForSingleObject(hThread1, 4000);//设置运行4s
//如果超出4s,则跳过该函数
if (signal != WAIT_OBJECT_0)
{
cout << "time out" << endl;
TerminateProcess(hThread1, -1);
}
CloseHandle(hThread1);
clock_t end_time = clock();
cout << "The run time is: " << (double)(end_time-start_time) / CLOCKS_PER_SEC << "s" << endl;
}
3000
5000
time out
The run time is: 4.001s

原本该函数应该睡眠8s后,退出,由于定时4s,所以超时后,直接退出了该函数。

#include<Windows.h>
#include<iostream>
#include<tchar.h>
#include<string>
#include<ctime>
using namespace std;
struct mytime
{
int t1;
int t2;
};
DWORD WINAPI f1(LPVOID lpParameter)
{
mytime* t = (mytime*)lpParameter;
cout << t->t1 << "
" << t->t2 << endl;
Sleep(t->t1 + t->t2);
return 0;
}
int main()
{
clock_t start_time = clock();
mytime T = { 3000,5000 };
HANDLE hThread1;
hThread1 = CreateThread(NULL, 0, f1, &T, 0, NULL);
int signal=WaitForSingleObject(hThread1, INFINITE);//一直等到f1函数运行完
if (signal != WAIT_OBJECT_0)
{
cout << "time out" << endl;
TerminateProcess(hThread1, -1);
}
CloseHandle(hThread1);
clock_t end_time = clock();
cout << "The run time is: " << (double)(end_time-start_time) / CLOCKS_PER_SEC << "s" << endl;
}
3000
5000
The run time is: 8.001s

如果不设置定时,那么就会直到该函数运行8s后,自动退出

最后

以上就是单薄西牛最近收集整理的关于C++设置一个函数的运行时间,如果超时,就跳过该函数的全部内容,更多相关C++设置一个函数内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(100)

评论列表共有 0 条评论

立即
投稿
返回
顶部