您的位置:首页 > 编程语言 > C语言/C++

c++中常用的计算程序运行时间的方法

2015-08-25 12:33 731 查看
方法1:
计时函数是clock(),而与其相关的数据类型是clock_t(头文件是time.h)。函数定义原型为:clock_t clock(void);

这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,在MSDN中称之为挂钟时间(wal-clock)。

clock_t是一个长整形数。另外在time.h文件中,还定义了一个常量CLOCKS_PER_SEC,它用来表示一秒钟会有多少个时钟计时单元,因此,我们就可以使用公式clock()/CLOCKS_PER_SEC来计算一个进程自身的运行时间。

给个例子:

#include "stdafx.h"
#include <time h="">
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
clock_t start,end;
double totaltime;
start = clock();
...//程序主代码
end = clock();
totaltime = (double)(end - start)/CLOCKS_PER_SEC;
cout<<"程序运行时间为:"<<totaltime<<"秒!"<<endl;
return 0;
}


方法2:

使用GetTickCount()函数,头文件是<windows.h>,GetTickCount函数返回从系统运行到现在所经历的时间(类型是DWORD),单位是毫秒,因为DWORD表示范围的限制,所以系统的运行时间表示不能超过DWORD限制。

给个例子:


#include "stdafx.h"
#include <windows h="">
//#include <time h="">
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
DWORD start = GetTickCount();
...//程序主代码
DWORD end = GetTickCount();
cout<<"程序运行时间为:"<<(end - start)<<"毫秒!"<<endl;
return 0;
}


方法3:

time_t类,头文件是<ctime>,精确到秒。

给个例子:

#include "stdafx.h"
//#include <windows h="">
//#include <time h="">
#include <ctime>
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
time_t start = 0,end = 0;
time(&start);
...//程序主代码
time(&end);
cout<<"程序运行时间为:"<<(end - start)<<"秒!"<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: