C++程序运行时间计算
1.如果只是要计算程序运行的时间,不需要那么复杂。<windows.h>中的GetTickCount()就是干这个的。TimeStart=GetTickCount();
.......
TimeEnd=GetTickCount();
TimeUsed=TimeEnd-TimeStart;
2.#include<stdio.h>
#include<time.h>
#include<conio.h>
int main()
{
time_t stime,etime;
time(&stime);/*get start time*/
getch();/*Access*/
time(&etime);/*get end time*/
printf("%ld\n",etime-stime);
getch();
return0;
}
3.class CTimer
{
public:
CTimer(){QueryPerformanceFrequency(&m_Frequency);Start();}
void Start(){QueryPerformanceCounter(&m_StartCount);}
double End(){LARGE_INTEGER
CurrentCount;QueryPerformanceCounter(&CurrentCount);return
double(CurrentCount.LowPart-m_StartCount.LowPart)/
(double)m_Frequency.LowPart;}
private:
LARGE_INTEGER m_Frequency;
LARGE_INTEGER m_StartCount;
};
4.VC的话有profile,在链接属性页勾选profile项,然后profile(在编译菜单下),各个函数时间都出来了
5.#include<iostream>
#include<ctime>
using namespace std;
int max(int x,int y)
{
return(x>y)?x:y;
}
int main()
{
const double begin=(double)clock()/CLK_TCK;
for(int i=10000;i>0;i--)
for(int j=10000;j>0;j--)
max(i,j);
const double end=(double)clock()/CLK_TCK;
利用printf函数输出日历
cout<<begin<<""<<end;
return0;
}
6.要最精确的有
LARGE_INTEGER limtp;
QueryPerformanceFrequency(&limtp);//获得当前的计数频率,即每秒进行多少次计数
QueryPerformanceCounter(&limtp);//获取当前计数次数
基于cpu级的
时间是
(计数获取计数次数-开始获取计数次数)/(用QueryPerformanceFrequency获取的limtp.QuadPart)
下面列出简单的例子
#include<ctime>//计时用的头文件
#include<iostream>
using namespace std;
int main()
{
time_t start,end,time;/*注意计时所用的变量名称*/
/*程序开始执行,开始计时*/
start=clock();
/*程序执行过程……*/
for(int i=0;i<=100000;i++)cout<<i<<'';
cout<<endl;
/*程序结束执行,结束计时*/
end=clock();
time=end-start;//这里的时间是计算机内部时间
cout<<endl<<""time:"<<time<<endl;
system("pause");
return0;
}
其它:
Include head file time.h,though it's a C include file,C++certainly can use it.
Under C++,you can include<ctime>instead of<time.h>
_____________________________________________________
time.h
@函数名称:localtime
函数原型:struct tm*localtime(const time_t*timer)
函数功能:返回一个以tm结构表达的机器时间信息
函数返回:以tm结构表达的时间,结构tm定义如下:
struct tm{
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
};
参数说明:timer-使用time()函数获得的机器时间
所属文件:<time.h>
#include<time.h>
#include<stdio.h>
#include<dos.h>
int main()
{
time_t timer;
struct tm*tblock;
timer=time(NULL);
tblock=localtime(&timer);
printf("Local time is:%s",asctime(tblock));
return0;
}
@函数名称:asctime
函数原型:char*asctime(struct tm*ptr)
函数功能:得到机器时间(日期时间转换为ASCII码)
函数返回:返回的时间字符串格式为:星期,月,日,小时:分:秒,年参数说明:结构指针ptr应通过函数localtime()和gmtime()得到所属文件:<time.h>
#include<stdio.h>
#include<string.h>
#include<time.h>
int main()
{
struct tm t;
char str[80];
<_sec=1;
<_min=3;
<_hour=7;
<_mday=22;
<_mon=11;
<_year=56;
<_wday=4;
<_yday=0;
<_isdst=0;