zoukankan      html  css  js  c++  java
  • clock()、time()、clock_gettime()和gettimeofday()函数的用法和区别【转】

    转自:http://www.cnblogs.com/krythur/archive/2013/02/25/2932647.html

    转自http://blog.sina.com.cn/s/blog_790f5ae10100rwd3.html

    一)ANSI clock函数 


    1)概述:
    clock 函数的返回值类型是clock_t,它除以CLOCKS_PER_SEC来得出时间,一般用两次clock函数来计算进程自身运行的时间.

    ANSI clock有三个问题:
    1)如果超过一个小时,将要导致溢出.
    2)函数clock没有考虑CPU被子进程使用的情况.
    3)也不能区分用户空间和内核空间.

    所以clock函数在linux系统上变得没有意义.

    2)测试
    编写test1.c程序,测试采用clock函数的输出与time程序的区别.

    vi test1.c
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>

    int main( void )
    {
       long i=1000L;
       clock_t start, finish;
       double  duration;
       printf( "Time to do %ld empty loops is ", i );
       start = clock();
       while (--i){
        system("cd");
       }
       finish = clock();
       duration = (double)(finish - start) / CLOCKS_PER_SEC;
       printf( "%f seconds ", duration );
       return 0;
    }

    gcc test1.c -o test1

    time ./test1
    Time to do 1000 empty loops is 0.180000 seconds

    real    0m3.492s
    user    0m0.512s
    sys     0m2.972s

    3)总结:
    (1)程序调用 system("cd");,这里主要是系统模式子进程的消耗,test1程序不能体现这一点.
    (2)0.180000 seconds秒的消耗是两次clock()函数调用除以CLOCKS_PER_SEC.
    (3)clock()函数返回值是一个相对时间,而不是绝对时间.
    (4)CLOCKS_PER_SEC是系统定义的宏,由GNU标准库定义为1000000.


    二)times()时间函数

    1)概述:

    原型如下:
    clock_t times(struct tms *buf);

    tms结构体如下:
    strace tms{
     clock_t tms_utime;
     clock_t tms_stime;
     clock_t tms_cutime;
     clock_t tms_cstime;
    }

    注释:
    tms_utime记录的是进程执行用户代码的时间.
    tms_stime记录的是进程执行内核代码的时间.
    tms_cutime记录的是子进程执行用户代码的时间.
    tms_cstime记录的是子进程执行内核代码的时间.


    2)测试:

    vi test2.c
    #include <sys/times.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <unistd.h>

    static void do_cmd(char *);
    static void pr_times(clock_t, struct tms *, struct tms *);

    int main(int argc, char *argv[]){
            int i;
            for(i=1; argv[i]!=NULL; i++){
                    do_cmd(argv[i]);
            }
            exit(1);
    }
    static void do_cmd(char *cmd){
            struct tms tmsstart, tmsend;
            clock_t start, end;
            int status;
            if((start=times(&tmsstart))== -1)
                    puts("times error");
            if((status=system(cmd))<0)
                    puts("system error");
            if((end=times(&tmsend))== -1)
                    puts("times error");
            pr_times(end-start, &tmsstart, &tmsend);
            exit(0);
    }
    static void pr_times(clock_t real, struct tms *tmsstart, struct tms *tmsend){
            static long clktck=0;
            if(0 == clktck)
                    if((clktck=sysconf(_SC_CLK_TCK))<0)
                               puts("sysconf err");
            printf("real:%7.2f ", real/(double)clktck);
            printf("user-cpu:%7.2f ", (tmsend->tms_utime - tmsstart->tms_utime)/(double)clktck);
            printf("system-cpu:%7.2f ", (tmsend->tms_stime - tmsstart->tms_stime)/(double)clktck);
            printf("child-user-cpu:%7.2f ", (tmsend->tms_cutime - tmsstart->tms_cutime)/(double)clktck);
            printf("child-system-cpu:%7.2f ", (tmsend->tms_cstime - tmsstart->tms_cstime)/(double)clktck);
    }

    编译:
    gcc test2.c -o test2

    测试这个程序:
    time ./test2 "dd if=/dev/zero f=/dev/null bs=1M count=10000"
    10000+0 records in
    10000+0 records out
    10485760000 bytes (10 GB) copied, 4.93028 s, 2.1 GB/s
    real:   4.94
    user-cpu:   0.00
    system-cpu:   0.00
    child-user-cpu:   0.01
    child-system-cpu:   4.82

    real    0m4.943s
    user    0m0.016s
    sys     0m4.828s


    3)总结:
    (1)通过这个测试,系统的time程序与test2程序输出基本一致了.
    (2)(double)clktck是通过clktck=sysconf(_SC_CLK_TCK)来取的,也就是要得到user-cpu所占用的时间,就要用
    (tmsend->tms_utime - tmsstart->tms_utime)/(double)clktck);
    (3)clock_t times(struct tms *buf);返回值是过去一段时间内时钟嘀嗒的次数.
    (4)times()函数返回值也是一个相对时间.

    三)实时函数clock_gettime

    在POSIX1003.1中增添了这个函数,它的原型如下:
    int clock_gettime(clockid_t clk_id, struct timespec *tp);

    它有以下的特点:
    1)它也有一个时间结构体:timespec ,timespec计算时间次数的单位是十亿分之一秒.
    strace timespec{
     time_t tv_sec;
     long tv_nsec;
    }

    2)clockid_t是确定哪个时钟类型.

    CLOCK_REALTIME: 标准POSIX实时时钟
    CLOCK_MONOTONIC: POSIX时钟,以恒定速率运行;不会复位和调整,它的取值和CLOCK_REALTIME是一样的.
    CLOCK_PROCESS_CPUTIME_ID和CLOCK_THREAD_CPUTIME_ID是CPU中的硬件计时器中实现的.


    3)测试:
    #include<time.h>
    #include<stdio.h>
    #include<stdlib.h>

    #define MILLION 1000000


    int main(void)
    {
            long int loop = 1000;
            struct timespec tpstart;
            struct timespec tpend;
            long timedif;

            clock_gettime(CLOCK_MONOTONIC, &tpstart);

            while (--loop){
                    system("cd");
            }

            clock_gettime(CLOCK_MONOTONIC, &tpend);
            timedif = MILLION*(tpend.tv_sec-tpstart.tv_sec)+(tpend.tv_nsec-tpstart.tv_nsec)/1000;
            fprintf(stdout, "it took %ld microseconds ", timedif);

            return 0;
    }

    编译:
    gcc test3.c -lrt -o test3

    计算时间:
    time ./test3
    it took 3463843 microseconds

    real    0m3.467s
    user    0m0.512s
    sys     0m2.936s


    四)时间函数gettimeofday()

    1)概述:
    gettimeofday()可以获得当前系统的时间,是一个绝对值

    原型如下:
    int gettimeofday ( struct timeval * tv , struct timezone * tz )

    timeval结型体的原型如下:
    struct timeval {
                   time_t      tv_sec;    
                   suseconds_t tv_usec;   
               };

    所以它可以精确到微秒


    测试:
    #include <sys/time.h>
    #include <stdio.h>
    #include <unistd.h>
    int
    main(){
            int i=10000000;
            struct timeval tvs,tve;
            gettimeofday(&tvs,NULL);
            while (--i);
            gettimeofday(&tve,NULL);
            double span = tve.tv_sec-tvs.tv_sec + (tve.tv_usec-tvs.tv_usec)/1000000.0;
            printf("time: %.12f ",span);
            return 0;
    }

    gcc test5.c
    ./a.out
    time: 0.041239000000

    五)四种时间函数的比较

    1)精确度比较:

    以下是各种精确度的类型转换:
    1秒=1000毫秒(ms), 1毫秒=1/1000秒(s);
    1秒=1000000 微秒(μs), 1微秒=1/1000000秒(s);
    1秒=1000000000 纳秒(ns),1纳秒=1/1000000000秒(s);


    2)
    clock()函数的精确度是10毫秒(ms)
    times()函数的精确度是10毫秒(ms)
    gettimofday()函数的精确度是微秒(μs)
    clock_gettime()函数的计量单位为十亿分之一,也就是纳秒(ns)


    3)测试4种函数的精确度:

    vi test4.c


    #include    <stdio.h>
    #include    <stdlib.h>
    #include    <unistd.h>
    #include    <time.h>
    #include    <sys/times.h>
    #include    <sys/time.h>
    #define WAIT for(i=0;i<298765432;i++);
    #define MILLION    1000000
        int
    main ( int argc, char *argv[] )
    {
        int i;
        long ttt;
        clock_t s,e;
        struct tms aaa;



        s=clock();
        WAIT;
        e=clock();
        printf("clock time : %.12f ",(e-s)/(double)CLOCKS_PER_SEC);


        long tps = sysconf(_SC_CLK_TCK);
        s=times(&aaa);
        WAIT;
        e=times(&aaa);
        printf("times time : %.12f ",(e-s)/(double)tps);


        struct timeval tvs,tve;
        gettimeofday(&tvs,NULL);
        WAIT;
        gettimeofday(&tve,NULL);
        double span = tve.tv_sec-tvs.tv_sec + (tve.tv_usec-tvs.tv_usec)/1000000.0;
        printf("gettimeofday time: %.12f ",span);


        struct timespec tpstart;
        struct timespec tpend;

        clock_gettime(CLOCK_REALTIME, &tpstart);
        WAIT;
        clock_gettime(CLOCK_REALTIME, &tpend);
        double timedif = (tpend.tv_sec-tpstart.tv_sec)+(tpend.tv_nsec-tpstart.tv_nsec)/1000000000.0;
        printf("clock_gettime time: %.12f ", timedif);

        return EXIT_SUCCESS;
    }

    gcc -lrt test4.c -o test4
    debian:/tmp# ./test4
    clock time : 1.190000000000
    times time : 1.180000000000
    gettimeofday time: 1.186477000000
    clock_gettime time: 1.179271718000

    六)内核时钟

    默认的Linux时钟周期是100HZ,而现在最新的内核时钟周期默认为250HZ.
    如何得到内核的时钟周期呢?
    grep ^CONFIG_HZ /boot/config-2.6.26-1-xen-amd64

    CONFIG_HZ_250=y
    CONFIG_HZ=250

    结果就是250HZ.

    而用sysconf(_SC_CLK_TCK);得到的却是100HZ
    例如:

    #include    <stdio.h>
    #include    <stdlib.h>
    #include    <unistd.h>
    #include    <time.h>
    #include    <sys/times.h>
    #include    <sys/time.h>

    int
    main ( int argc, char *argv[] )
    {

        long tps = sysconf(_SC_CLK_TCK);
        printf("%ld ", tps);
       
        return EXIT_SUCCESS;
    }

    为什么得到的是不同的值呢?
    因为sysconf(_SC_CLK_TCK)和CONFIG_HZ所代表的意义是不同的.
    sysconf(_SC_CLK_TCK)是GNU标准库的clock_t频率.
    它的定义位置在:/usr/include/asm/param.h

    例如:
    #ifndef HZ
    #define HZ 100
    #endif

    最后总结一下内核时间:
    内核的标准时间是jiffy,一个jiffy就是一个内部时钟周期,而内部时钟周期是由250HZ的频率所产生中的,也就是一个时钟滴答,间隔时间是4毫秒(ms).

    也就是说:
    1个jiffy=1个内部时钟周期=250HZ=1个时钟滴答=4毫秒

    每经过一个时钟滴答就会调用一次时钟中断处理程序,处理程序用jiffy来累计时钟滴答数,每发生一次时钟中断就增1.
    而每个中断之后,系统通过调度程序跟据时间片选择是否要进程继续运行,或让进程进入就绪状态.

    最后需要说明的是每个操作系统的时钟滴答频率都是不一样的,LINUX可以选择(100,250,1000)HZ,而DOS的频率是55HZ.

    七)为应用程序计时

    用time程序可以监视任何命令或脚本占用CPU的情况.

    1)bash内置命令time
    例如:
    time sleep 1

    real    0m1.016s
    user    0m0.000s
    sys     0m0.004s


    2)/usr/bin/time的一般命令行
    例如:
    ime sleep 1
    0.00user 0.00system 0:01.01elapsed 0%CPU (0avgtext+0avgdata 0maxresident)k
    0inputs+0outputs (1major+176minor)pagefaults 0swaps

    注:
    在命令前加上斜杠可以绕过内部命令.
    /usr/bin/time还可以加上-v看到更具体的输出:
    ime -v sleep 1
            Command being timed: "sleep 1"
            User time (seconds): 0.00
            System time (seconds): 0.00
            Percent of CPU this job got: 0%
            Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.00
            Average shared text size (kbytes): 0
            Average unshared data size (kbytes): 0
            Average stack size (kbytes): 0
            Average total size (kbytes): 0
            Maximum resident set size (kbytes): 0
            Average resident set size (kbytes): 0
            Major (requiring I/O) page faults: 0
            Minor (reclaiming a frame) page faults: 178
            Voluntary context switches: 2
            Involuntary context switches: 0
            Swaps: 0
            File system inputs: 0
            File system outputs: 0
            Socket messages sent: 0
            Socket messages received: 0
            Signals delivered: 0
            Page size (bytes): 4096
            Exit status: 0
           
    这里的输出更多来源于结构体rusage.

    最后,我们看到real time大于user time和sys time的总和,这说明进程不是在系统调用中阻塞,就是得不到运行的机会.
    而sleep()的运用,也说明了这一点.

  • 相关阅读:
    面试(5)
    面试(五)
    面试(4)
    面试(四)
    面试(三)
    面试(2,3)
    利用session控制 长时间未操作自动退出登录
    一次性清除所有session
    动态引进js文件
    Vue--findIndex方法的使用原理
  • 原文地址:https://www.cnblogs.com/sky-heaven/p/6077901.html
Copyright © 2011-2022 走看看