C++ 学习系列(一)测试程序运行时间—clock()

来源:互联网 发布:苹果电脑内存清理软件 编辑:程序博客网 时间:2024/05/18 02:58

计算程序运行时间 方法一

C++中的计时函数是clock(),而与其相关的数据类型是clock_t(头文件是time.h)。
函数定义原型为: clock_t clock(void);

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

clock_t:保存时间的数据类型,为长整形数。

#define CLOCKS_PER_SEC ((clock_t)1000) //单位转换,从ms到m #include <iostream> #include "time.h" //关键的头文件 #include "stdio.h" #include "stdlib.h"using namespace std;int main(){    clock_t start,finish;    double totalTime;    start=clock();     //测试主程序,注意也有可能放在主程序的循环里面,或者如果是视频的话,要放在循环里面。     //程序代码处     eg: forint i=1;i<100;i++)  { ...  }    finish=clock();    totalTime=(double)(finish-start)/CLOCKS_PER_SEC;    cout<<"花费时间为:"<<totalTime<<"s"<endl;     return 0;   }
原创粉丝点击