红联Linux门户
Linux帮助

Linux下对时间进行运算精确函数

发布时间:2014-03-23 21:54:26来源:红联作者:tioced
在Linux下对时间进行运算,如果是到秒级的,相信大家都用过time之类的函数实现了,但要更精确些呢?到毫秒、微秒级呢?

看看下面这段源代码就明白了:

引用:
#include
#include
#include

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 */
};


其它不用说了,大家应该都明白了吧?
文章评论

共有 3 条评论

  1. Lhhba 于 2014-03-24 08:46:07发表:

    好有难度

  2. xkin_z 于 2014-03-23 23:10:12发表:

    用shell不就可以吗

  3. xkin_z 于 2014-03-23 23:09:23发表:

    c啊