C++计算时间

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C++程序运行时间计算

1.如果只是要计算程序运行的时间,不需要那么复杂。中的GetTickCount()就是干这个的。TimeStart=GetTickCount();

.......

TimeEnd=GetTickCount();

TimeUsed=TimeEnd-TimeStart;

2.#include

#include

#include

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

#include

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;

cout<

return0;

}

6.要最精确的有

LARGE_INTEGER limtp;

QueryPerformanceFrequency(&limtp);//获得当前的计数频率,即每秒进行多少次计数

QueryPerformanceCounter(&limtp);//获取当前计数次数

基于cpu级的

时间是

(计数获取计数次数-开始获取计数次数)/(用QueryPerformanceFrequency获取的limtp.QuadPart)

下面列出简单的例子

#include//计时用的头文件

#include

using namespace std;

int main()

{

time_t start,end,time;/*注意计时所用的变量名称*/

/*程序开始执行,开始计时*/

start=clock();

/*程序执行过程……*/

for(int i=0;i<=100000;i++)cout<

cout<

/*程序结束执行,结束计时*/

end=clock();

time=end-start;//这里的时间是计算机内部时间

cout<

system("pause");

return0;

}

其它:

Include head file time.h,though it's a C include file,C++certainly can use it.

Under C++,you can includeinstead of

_____________________________________________________

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()函数获得的机器时间

所属文件:

#include

#include

#include

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()得到所属文件:

#include

#include

#include

int main()

{

struct tm t;

char str[80];

t.tm_sec=1;

t.tm_min=3;

t.tm_hour=7;

t.tm_mday=22;

t.tm_mon=11;

t.tm_year=56;

t.tm_wday=4;

t.tm_yday=0;

t.tm_isdst=0;

相关文档
最新文档