clock函数返回的值和CLOCKS_PER_SEC存在密不可分的关系,如果只是clock()/CLOCKS_PER_SEC返回的才是秒
#include <string.h>
#include <sys/time.h>//gettimeofday
#include <unistd.h>
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
struct timeval tv_time;
int i=0;
clock_t clock_start;
cout<<"CLOCKS_PER_SEC:"<<CLOCKS_PER_SEC<<endl;
clock_start=clock();
while(1)
{
/******************************///两种方式,计算程序运行的时间
//sleep(5);
/******************************///打印结果总是零
while( i<1000)
{
//gettimeofday(&tv_time,NULL);
usleep(1);
i++;
}
/******************************/
cout<<"Now time passed(s):"<<(clock()-clock_start)/CLOCKS_PER_SEC<<endl;
cout<<"Now time passed(ms):"<<(clock()-clock_start)<<endl;
i=0;
}
return 0;
}
/*解释:clock()函数是一个计算程序运行时间(其实简略的理解为占用CPU的使用时间)其实如果使用sleep函数,程序是放弃CPU的使用权,直到某个时间的到来,当然就不会存在占用CPU时间的时候,即使是一个计数的循环,对于CPU来说,也是微不足道的。*/
转载于:https://blog.51cto.com/fengyuzaitu/1902302