Linux系統(tǒng)下精確到微秒級的時間操作函數(shù)
Linux下對時間進(jìn)行運(yùn)算,如果是到秒級的,相信大家都用過time之類的函數(shù)實(shí)現(xiàn)了,但要更精確些呢?到毫秒、微秒級呢?
看看下面這段源代碼就明白了:
#include
#include
#include
void function()/*用來耗用一定的時間而已,無實(shí)際用處的函數(shù)*/
{
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函數(shù),函數(shù)里用到了這個結(jié)構(gòu):
struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* microseconds */
};