C++记录程序运行的时间

来源:互联网 发布:windows升级助手 编辑:程序博客网 时间:2024/06/05 16:26

一、用clock()计时函数

       该函数为C++典型计时函数,即为程序从启动到函数调用占用CPU的时间。该函数的返回值是从程序开启到程序调用clock()函数之间的CPU时钟计时单元数(clock tick)。

       数据类型保存形式:clock_t(长整形数)

       头文件:time.h

       常量CLOCKS_PER_SEC:一秒钟有多少个时钟计时单元

       注意:在计算(endTime - startTime)时候需要强制转化为double。由于clock_t是属于int64类型的数据。在做除法运算时,不足一秒会视为0.

#include <iostream>#include <time.h>using namespace std;int main() {clock_t startTime, endTime;startTime = clock();for (int i = 'a'; i <= 'z'; i++) {cout << i << endl;}endTime = clock();cout << "Time: " << (double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl;system("pause");}


二、用getTickCount()计时函数

       GetTickcount函数:它返回从操作系统启动到当前所经过的毫秒数,常常用来判断某个方法执行的时间,其函数原型是DWORD GetTickCount(void),返回值以32位的双字类型DWORD存储,因此可以存储的最大值是(2^32-1) ms约为49.71天,因此若系统运行时间超过49.71天时,这个数就会归0,MSDN中也明确的提到了:"Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days."。(摘抄自百度百科)

double time0 = static_cast<double>(getTickCount());// 将RGB转为灰度图cvtColor(pic, edges, CV_BGR2GRAY);// 进行模糊blur(edges, edges, Size(7, 7));// 进行边缘检测Canny(edges, edges, 0, 30, 3);// 计算时间time0 = ((double)getTickCount() - time0) / getTickFrequency();cout << "此方法运行时间为: " << time0 << "秒" << endl;




原创粉丝点击