zoukankan      html  css  js  c++  java
  • Linux时间函数之gettimeofday()函数之使用方法

    1.简介:

    在C语言中可以使用函数gettimeofday()函数来得到时间。它的精度可以达到微妙

    2.函数原型:

    #include<sys/time.h>

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

    3.说明:

    gettimeofday()会把目前的时间用tv 结构体返回,当地时区的信息则放到tz所指的结构中

    4.结构体:

    1>timeval

    struct  timeval{

       

           long  tv_sec;/*秒*/

           long  tv_usec;/*微妙*/

    };

    2>timezone 结构定义为:

    struct  timezone{

            int tz_minuteswest;/*和greenwich 时间差了多少分钟*/

            int tz_dsttime;/*type of DST correction*/

    }

    3>在gettimeofday()函数中tv或者tz都可以为空。如果为空则就不返回其对应的结构体。

    4>函数执行成功后返回0,失败后返回-1,错误代码存于errno中。

    5.程序实例:

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

    #include<unistd.h>

     

    int main()

    {

            struct  timeval    tv;

            struct  timezone   tz;

            gettimeofday(&tv,&tz);

     

            printf(“tv_sec:%d ”,tv.tv_sec);

            printf(“tv_usec:%d ”,tv.tv_usec);

            printf(“tz_minuteswest:%d ”,tz.tz_minuteswest);

            printf(“tz_dsttime:%d ”,tz.tz_dsttime);

    }

    说明:在使用gettimeofday()函数时,第二个参数一般都为空,因为我们一般都只是为了获得当前时间,而不用获得timezone的数值

    二.gettimeofday()函数的一个常用方法

    在测试程序时,往往需要了解程序执行所需的时间,在Linux中可以使用函数gettimeofday来得到时间.

    1.程序实例:

    测试调用delya()函数所需执行的时间(单位为微妙)

    #include<stdio.h>

    #include<sys/time.h>

    #include<unistd.h>

     

    int delay(int time)

    {

        int i,j;

       

        for(i =0;i<time;i++)

            for(j=0;j<5000;j++)

                ;

    }

     

    int main()

    {

            struct  timeval start;

            struct  timeval end;

           

            unsigned  long diff;

            gettimeofday(&start,NULL);

            delay(10);

            gettimeofday(&end,NULL);

    diff = 1000000 * (end.tv_sec-start.tv_sec)+ end.tv_usec-start.tv_usec;

            printf(“thedifference is %ld ”,diff);

            return 0;

           

    }

    说明:

    使用该方法就可以检测出调用delay()函数所使用的时间

  • 相关阅读:
    前端生成二维码插件jquery.qrcode.min.js
    Spring的PropertyPlaceholderConfigurer
    Mysql5.7.20安装随笔
    Tomcat配置虚拟目录(目录+文件)
    js中的特殊类型
    使用 adb 命令一次性为多个设备安装 apk
    高通工具使用指导书
    QXDM及QCAT软件使用入门指南V1.0
    CTS测试笔记
    Android adb shell启动应用程序的方法
  • 原文地址:https://www.cnblogs.com/zl1991/p/5530546.html
Copyright © 2011-2022 走看看