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?
-
1Duplicate: http://stackoverflow.com/questions/2731463/converting-jiffies-to-milli-seconds – Daenyth Oct 06 '10 at 19:34
-
2This isn't a duplicate as I cannot use the HZ define. – Brian Makin Oct 06 '10 at 19:48
4 Answers
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
.

- 4,474
- 40
- 55

- 62,604
- 14
- 116
- 151
-
I did read that 100 is always presented to userspace... but wasn't sure /proc counted as userspace :) – Brian Makin Oct 06 '10 at 22:43
-
I'm not certain I understand: does this mean that HZ is not actually the number that the questioner wanted? – Eric Seppanen Oct 07 '10 at 15:40
-
1HZ is the number I wanted... but it is a compiled in constant. As long as I'm running on the same machine I compiled for... all is good. But if I move to another machine without recompiling then it might have the wrong value. – Brian Makin Oct 08 '10 at 13:55
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

- 1
- 1

- 11,516
- 10
- 61
- 114
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.

- 785
- 10
- 18
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.

- 9,249
- 5
- 39
- 47