C++ 时间间隔

来源:互联网 发布:世界时差软件 编辑:程序博客网 时间:2024/06/11 20:46
#include<iostream>#include<time.h>using namespace std;int main(){  clock_t s,e;  s=clock();  for(int i=0; i< 100000;i++)  {    cout<<i<<endl;      }  e=clock();  cout<<"  "<<double(e-s)/CLOCKS_PER_SEC*1000<<"ms"<<endl;}

gettimeofday

使用C语言编写程序需要获得当前精确时间(UNIX到现在的时间),或者为执行计时,可以使用gettimeofday()函数。它的[1]:
#include <sys/time.h>
int gettimeofday(structtimeval*tv, struct timezone *tz);
其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果(若不使用则传入NULL即可)。
结构体timeval的定义为:
structtimeval{
long int tv_sec; // 秒数
long int tv_usec; // 微秒数
}
它获得的时间精确到微秒(1e-6 s)量级。在一段代码前后分别使用gettimeofday可以计算代码执行时间:
structtimevaltv_begin, tv_end;
gettimeofday(&tv_begin, NULL);
foo();
gettimeofday(&tv_end, NULL);
执行时间(微秒) = 1000000 * (tv_end.tv_sec - tv_begin.tv_sec) + tv_end.tv_usec - tv_begin.tv_usec;



原创粉丝点击