zoukankan      html  css  js  c++  java
  • linux --> 获取进程执行时间

    获取进程执行时间

    一、时间概念

      在linux下进行编程时,可能会涉及度量进程的执行时间。linux下进程的时间值分三种:

        时钟时间(real time):指进程从开始执行到结束,实际执行的时间。

        用户CPU时间(user CPU time):指进程中执行用户指令所用的时间,也包括子进程。

        系统CPU时间(system CPU time):指为进程执行内核程序所经历的时间,例如调用read和write内核方法时,消耗的时间就计入系统CPU时间。

    二、获取方法  

      有两种方法可以获取,第一种是用time命令,time 进程。第二种是通过在程序中进行记录,首先利用sysconf函数获取时钟滴答数,再用times获取tms结构。

    查看times函数,man 2 tms,得到tms结构定义和times函数声明如下:

    struct tms {
           clock_t tms_utime;  /* user time */
           clock_t tms_stime;  /* system time */
           clock_t tms_cutime; /* user time of children */
           clock_t tms_cstime; /* system time of children */
      };
    #include <sys/times.h>
    
     clock_t times(struct tms *buf);

    注意:此处计算的时间是时钟滴答数,需要除以系统时钟滴答数,得出实际的秒数。

    三、测试例子

    测试程序如下:

    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/times.h>
    #include <unistd.h>
    
    #define BUFFER_SIZE  4 * 1024 
    
    int main()
    {
        int sc_clk_tck;
        sc_clk_tck = sysconf(_SC_CLK_TCK);
    
        struct tms begin_tms, end_tms;
        clock_t begin, end;
        system("date");
        begin = times(&begin_tms);
        sleep(2);
        end = times(&end_tms);
    
        printf("real time: %lf
    ", (end - begin) / (double)sc_clk_tck);
        printf("user time: %lf
    ", (end_tms.tms_utime - begin_tms.tms_utime) / (double)sc_clk_tck);
        printf("sys time: %lf
    ", (end_tms.tms_stime - begin_tms.tms_stime) / (double)sc_clk_tck);
        printf("child user time: %lf
    ", (end_tms.tms_cutime - begin_tms.tms_cutime) / (double)sc_clk_tck);
        printf("child sys time: %lf
    ", (end_tms.tms_cstime - begin_tms.tms_cstime) / (double)sc_clk_tck);
        return 0;
    }

    测试结果如下所示:

    采用time命令,测试结果如下所示:

    其中real表示时钟时间,user表示用户CPU时间,sys表示系统CPU时间。time命令也可以用于系统的命令,如time ls、time ps等等。

    参考:http://www.cnblogs.com/Anker/p/3416288.html
  • 相关阅读:
    前端错误知识提示积累
    插件介绍之一:常用插件
    css小技巧积累
    设置网页地址栏小图标
    SEO优化篇——meta用法
    获取客户端的cookie
    come on,make a date progress bar together!
    教教你不用table制作出表格
    js实现快捷键绑定按钮点击事件
    Sublime Text3常用快捷键
  • 原文地址:https://www.cnblogs.com/jeakeven/p/5301096.html
Copyright © 2011-2022 走看看