CPU activity as percentage.

mal content artifact.one at googlemail.com
Sat Aug 4 00:36:01 PDT 2007


Hello.

I'm trying to write a function sys_cpu_percent() that
returns the current cpu usage as a percentage. I currently
have this:

double sys_cpu_percent()
{
  long cp_time[CPUSTATES];
  double used;
  double total;
  size_t len = sizeof(cp_time);

  if (sysctlbyname("kern.cp_time", cp_time, &len, 0, 0) < 0) return 0;

  used = cp_time[CP_USER] + cp_time[CP_NICE] + cp_time[CP_SYS] +
cp_time[CP_INTR];
  total = cp_time[CP_USER] + cp_time[CP_NICE] + cp_time[CP_SYS] +
cp_time[CP_INTR] + cp_time[CP_IDLE];

  return (used / total) * 100;
}

However the function always returns ~9%, even when
running a cpu intensive task in the background. Am I
missing something obvious here? Is there a better way
of doing this?

My system is uniprocessor, if that makes any difference.

thanks,
MC


More information about the freebsd-hackers mailing list