linux C++ clock()函数计算代码运行时间

在Windows Sleep()占用processor time,

#include <stdio.h>  
#include <time.h>  
#include <windows.h>  
  
int main()  
{  
    printf("The start clock is: %ld\n", clock());  
    Sleep(2000);  
    printf("The end clock is: %ld\n", clock());  
  
    return 0;  
}  

Linux下的sleep()不占用processor time,这可能与底层的sleep()实现机制的不同所导致的。

linux环境下clock() 不能计算sleep()占用的时间

#include <iostream>
#include <time.h>
#include <unistd.h>
using namespace std;
int i=300;
int main()
{
   clock_t  begin ,end;
   begin=clock();
while(i--){
        //usleep(3);//linux环境下clock() 不能计算sleep()占用的时间
         printf("test----\n");
}
       printf("test----\n");
/*   for(int i=0;i<10000;i++)
   {
       for(int j=0;j<10000;j++)
       {}
   }*/
   end=clock();
   cout<<"sizeof(clock_t) is:"<<sizeof(clock_t)<<endl;
   cout<<"time used:"<< (double)(end - begin) / CLOCKS_PER_SEC << endl;//系统定义一个符号常量----CLOCKS_PER_SEC,该常量等于每秒钟包含的系统时间单位数  在linux系统下,CLOCKS_PER_SEC的值可能有所不同,目前使用的linux打印出来的值是1000000,表示的是微秒。这一点需要注意。


 
   cout<<"begin is:"<<begin<<endl;
   cout<<"end  is:"<<end<<endl;
   cout<<"CLOCKS_PER_SEC is:"<<CLOCKS_PER_SEC<<endl;
}

猜你喜欢

转载自blog.csdn.net/weixin_42627035/article/details/85725882