时间函数 gettimeofday

Linux下可以使用gettimeofday()来查看当前时间,这个函数会计算从1970年1月1号00:00(格林威治时间)到当前的时间跨度。其函数原型如下

函数原型:

#include<sys/time.h>

int gettimeofday(struct timeval *tv,struct timezone *tz)   

该函数所算出的时间跨度会存放在第一个参数结构体变量tv里,这个参数的类型定义如下,

struct timeval

{

        long tv_sec;             //

        long tv_usec;   //微秒

}

代码:

如下是该函数一个简单应用,计算一个函数运算时间

#include<stdio.h>

#include<sys/time.h>

void cntTest()          //定义一个需要计算运行时间的函数

{

        int i,j;

        for(i=0;i<100;i++){

                for(j=0;j<1000;j++){

                }

        }

}

int main()

{

        long difference;

        struct timeval timestart;       //函数调用之前时间

        struct timeval timestop;        //函数调用之后时间

        gettimeofday(&timestart,NULL);

        cntTest();

        gettimeofday(&timestop,NULL);

        difference=1000000*(timestop.tv_sec-timestart.tv_sec)+(timestop.tv_usec-timestart.tv_usec);                //计算出的结果,以us为单位

        printf("time start: sec = %ld,usec = %ld\n",timestart.tv_sec,timestart.tv_usec);

        printf("time stop: sec = %ld,usec = %ld\n",timestop.tv_sec,timestop.tv_usec);

        printf("diffefence: %ld us\n",difference);

        return 0;

}

运行结果:

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值