一,时间函数知识点总结
二,计算程序运行时间的代码实例(本人课堂实例)
#include <iostream>
#include<ctime> //时间头文件
using namespace std;
int main()
{
const int Count1 = 10; //声明常量
const int Count2 = 1000000;//声明常量
const int Count3 = 1000;//声明常量
int i,j; //声明变量
float sum = 0.0;
time_t start_time, finish_time; //声明时间变量
clock_t time_req; //定义一个保存时间的变量
for(i=0;i<Count1; i++) //循环1
sum+=1.0/Count1; //求和1
cout << "The sum of the for - loop(COUNT=10) is : " <<sum << endl<<endl; //输出第一个求和结果
sum=0.0;
for(i=0;i< Count2;i++) //循环2
sum+=1.0/Count2; //求和2
cout<< "The sum of the for -loop(COUNT=1000000) is : " << sum << endl<<endl; //输出第二个求和结果
time_req = clock();//对从开始到当前计时
time(&start_time);//当前时间(开始时间)
sum = 0.0;
for(i=0; i<Count3; i++)//循环
for(j=0; j<Count3;j++)
sum+=(1.0/Count3)*(1.0/Count3);
cout<< "The sum of the for-loop(COUNT=1000*1000) is : "<<sum<<endl;
time(&finish_time); //当前时间与1970.01.01时间差(秒)
cout << " Time required(time) = " << difftime(finish_time, start_time) << "seconds"<<endl;//求时间差(即执行循环所需时间)
time_req = clock() - time_req;//运行的时间
cout<< "Time required(clock) = " << time_req << " clocks" <<endl;//输出循环运行时间,单位毫秒
cout<< "Time required(clock) = " << (float)time_req/CLOCKS_PER_SEC << "seconds" <<endl <<endl;//输出循环行时间,CLOCKS_PER_SEC表示一秒钟会有多少个时钟计时单位
time_req = clock();//对从开始到当前计时
sum = 0.0;
for(i=0; i<Count2; i++)//循环
for(j=0; j<Count3; j++)
sum+= (1.0/Count2)*(1.0/Count3);//求和
cout<< "The sum of the for -loop(COUNT=1000000*1000) is : " <<sum <<endl;//输出循环求和结果
time(&finish_time);//完成的系统时间
cout << "Time required(time) = " << difftime(finish_time, start_time) << "seconds" <<endl;//输出执行时间
time_req =clock() - time_req;//运行时间
cout<< "Time required(clock) = " << time_req << "clocks" <<endl;//输出运行时间,单位毫秒
cout<< "Time required(clock) = " << (float) time_req/CLOCKS_PER_SEC << "seconds" <<endl;//输出循环运行时间,单位秒
return 0;
}