一种简单的C++记时方法和等待方法

#include<unistd.h>//for sleep
#include <iostream>
#include<time.h>//for clock()
using namespace std;

int main(int argc,char** argv)
{
	clock_t start_time,end_time;
	double totaltime;
	start_time=clock();
	for(int i=0;i<20;i++)
	{
		for(double j=0;j<10000;j++)
		for(double k=0;k<10000;k++) double m=10;			
	}
	end_time=clock();
   	totaltime=(double)(end_time-start_time)/CLOCKS_PER_SEC;
	cout<<"totaltime= "<<totaltime<<"second "<<endl;
	sleep(1);
	end_time=clock();
	totaltime=(double)(end_time-start_time)/CLOCKS_PER_SEC;
	cout<<"totaltime after sleep(1)= "<<totaltime<<"second"<<endl;
}

函数输出结果为:

totaltime= 3.33158second 
totaltime after sleep(1)= 3.33169second

由此发现一个需要注意的地方是,当使用了sleep()函数时,clock(),也停止了时钟计数,即进入了睡眠状态

猜你喜欢

转载自blog.csdn.net/qq_34122731/article/details/92195230
今日推荐