sysinfo系统调用在linux上返回错误的加载平均值

前端之家收集整理的这篇文章主要介绍了sysinfo系统调用在linux上返回错误的加载平均值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个C程序打印一些系统统计信息.
#include <sys/sysinfo.h>
#include <stdio.h>

int main() {
  int days,hours,mins;
  struct sysinfo sys_info;

  if(sysinfo(&sys_info) != 0)
    perror("sysinfo");

  // Uptime
  days = sys_info.uptime / 86400;
  hours = (sys_info.uptime / 3600) - (days * 24);
  mins = (sys_info.uptime / 60) - (days * 1440) - (hours * 60);

  printf("Uptime: %ddays,%dhours,%dminutes,%ldseconds\n",days,mins,sys_info.uptime % 60);

  // Load Averages for 1,5 and 15 minutes
  printf("Load Avgs: 1min(%ld) 5min(%ld) 15min(%ld)\n",sys_info.loads[0],sys_info.loads[1],sys_info.loads[2]);

  printf("Total Ram: %lluk\tFree: %lluk\n",sys_info.totalram *(unsigned long long)sys_info.mem_unit / 1024,sys_info.freeram *(unsigned long long)sys_info.mem_unit/ 1024);


  // Number of processes currently running.
  printf("Number of processes: %d\n",sys_info.procs);

  return 0;
}

我的问题是负载平均值不同于/ proc / loadavg

./a.out 
Uptime: 1days,4hours,1minutes,16seconds
Load Avgs: 1min(13248) 5min(14880) 15min(11840)
Total Ram: 2052956k Free: 188104k
Number of processes: 265

为什么?我打印13248但“top”或“cat / proc / loadavg”给出0.24.问题是什么?

解决方法

调用不会返回“错误”值.请注意,类型是整数,因此不能返回正常运行时打印的浮点数.

有关如何解释返回值以及如何转换为更熟悉的浮点数的调查,请参阅this thread.

我的猜测(在阅读链接之前)是它的表现为按比例缩放65,535(216),这似乎也是他们发现的.因此除以65536.0,或者更清洁(如注释中所指出的)使用SI_LOAD_SHIFT常量并除以(浮点)(1<< SI_LOAD_SHIFT).

猜你在找的Linux相关文章