Brian Makin
Brian Makin

Reputation: 907

convert jiffies to seconds

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 another machine which has a different configured value. Is there any way to get the value of HZ from userspace at runtime?

Upvotes: 11

Views: 11833

Answers (4)

MarkR
MarkR

Reputation: 63538

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.

Upvotes: 7

Otheus
Otheus

Reputation: 1032

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.

Upvotes: 0

William Breathitt Gray
William Breathitt Gray

Reputation: 11966

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

Upvotes: 4

Jérôme Pouiller
Jérôme Pouiller

Reputation: 10197

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.

Upvotes: 0

Related Questions