歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux基礎知識 >> Linux系統下精確到微秒級的時間操作函數

Linux系統下精確到微秒級的時間操作函數

日期:2017/3/2 15:32:37   编辑:Linux基礎知識
Linux下對時間進行運算,如果是到秒級的,相信大家都用過time之類的函數實現了,但要更精確些呢?到毫秒、微秒級呢?

看看下面這段源代碼就明白了:

#include <sys/time.h>
#include <stdio.h>
#include <math.h>

void function()/*用來耗用一定的時間而已,無實際用處的函數*/
{
unsigned int i,j;
double y;
for(i=0;i<10000;i++)
for(j=0;j<10000;j++)
y=sin((double)i);
}

int main(int argc, char ** argv)
{
struct timeval tpstart,tpend;
float timeuse;

gettimeofday(&tpstart,NULL);
function();
gettimeofday(&tpend,NULL);
timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;
timeuse/=1000000;
printf("Used Time:%f\n",timeuse);
exit(0);
}

主要是用到了gettimeofday函數,函數裡用到了這個結構:

struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* microseconds */
};
Copyright © Linux教程網 All Rights Reserved