convert jiffies to seconds

后端 未结 4 544
悲&欢浪女
悲&欢浪女 2021-01-04 18:28

I\'ve got a piece of userspace code which is parsing /proc/PID/task/TID/stat to get the cpu usage. I can use HZ to get the jiffies per second but this code could move to an

相关标签:
4条回答
  • 2021-01-04 19:14

    Source of "ps" command include file <linux/param.h> to get value of HZ.

    They also look for an "ELF note" with number 17 to find value of HZ (sysinfo.c):

     //extern char** environ;
    
     /* for ELF executables, notes are pushed before environment and args */
     static unsigned long find_elf_note(unsigned long findme){
       unsigned long *ep = (unsigned long *)environ;
       while(*ep++);
       while(*ep){
         if(ep[0]==findme) return ep[1];
         ep+=2;
       }
       return NOTE_NOT_FOUND;
     }
     [...]
     hz = find_elf_note(17);
    

    I have to admit it look weird for me since ELF notes is a section defined during compilation.

    0 讨论(0)
  • 2021-01-04 19:16

    For shell-scripting, etc, use getconf CLK_TCK from the command-line. Use can use this to pass that parameter in as an environment variable or on the command-line.

    main(int argc, char **argv) { 
        unsigned long clk_tck = atol(
            getenv("CLK_TCK") || "0"
        ) || sysconf(_SC_CLK_TCK) ;
        ... /* your code */
    

    This uses the sysconf as above, but allows you to override it with an environment variable, which can be set with the above command.

    0 讨论(0)
  • 2021-01-04 19:19

    To clarify the math behind MarkR's answer:

    sysconf(_SC_CLK_TCK) will get you jiffies per second. Divide jiffies by the number you get from sysconf(_SC_CLK_TCK) to get the total number of seconds.

          jiffies                      jiffies              seconds
    --------------------    =     -----------------    =    -------    =    seconds
    sysconf(_SC_CLK_TCK)          (jiffies/second)             1
    
    0 讨论(0)
  • 2021-01-04 19:21

    You divide it by the number you get from sysconf(_SC_CLK_TCK).

    However, I think this is probably always 100 under Linux regardless of the actual clock tick, it's always presented to userspace as 100.

    See man proc(5).

    0 讨论(0)
提交回复
热议问题