cpu.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /* See LICENSE file for copyright and license details. */
  2. #include <errno.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include "../util.h"
  6. #if defined(__linux__)
  7. #include <inttypes.h>
  8. #include <stdint.h>
  9. const char *
  10. cpu_freq(void)
  11. {
  12. uint64_t freq;
  13. /* in kHz */
  14. if (pscanf("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq",
  15. "%"SCNu64, &freq) != 1) {
  16. return NULL;
  17. }
  18. return fmt_human_10(freq * 1000, "Hz");
  19. }
  20. const char *
  21. cpu_perc(void)
  22. {
  23. static int valid;
  24. static long double a[7];
  25. long double b[7];
  26. memcpy(b, a, sizeof(b));
  27. /* cpu user nice system idle iowait irq softirq */
  28. if (pscanf("/proc/stat", "%*s %Lf %Lf %Lf %Lf %Lf %Lf %Lf",
  29. &a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6]) != 7) {
  30. return NULL;
  31. }
  32. if (!valid) {
  33. valid = 1;
  34. return NULL;
  35. }
  36. return bprintf("%d%%", (int)(100 *
  37. ((b[0] + b[1] + b[2] + b[5] + b[6]) -
  38. (a[0] + a[1] + a[2] + a[5] + a[6])) /
  39. ((b[0] + b[1] + b[2] + b[3] + b[4] + b[5] + b[6]) -
  40. (a[0] + a[1] + a[2] + a[3] + a[4] + a[5] + a[6]))));
  41. }
  42. #elif defined(__OpenBSD__)
  43. #include <sys/param.h>
  44. #include <sys/sched.h>
  45. #include <sys/sysctl.h>
  46. const char *
  47. cpu_freq(void)
  48. {
  49. int freq, mib[2];
  50. size_t size;
  51. mib[0] = CTL_HW;
  52. mib[1] = HW_CPUSPEED;
  53. size = sizeof(freq);
  54. /* in MHz */
  55. if (sysctl(mib, 2, &freq, &size, NULL, 0) < 0) {
  56. warn("sysctl 'HW_CPUSPEED':");
  57. return NULL;
  58. }
  59. return fmt_human_10((size_t)freq * 1000 * 1000, "Hz");
  60. }
  61. const char *
  62. cpu_perc(void)
  63. {
  64. int mib[2];
  65. static int valid;
  66. static long int a[CPUSTATES];
  67. long int b[CPUSTATES];
  68. size_t size;
  69. mib[0] = CTL_KERN;
  70. mib[1] = KERN_CPTIME;
  71. size = sizeof(a);
  72. memcpy(b, a, sizeof(b));
  73. if (sysctl(mib, 2, &a, &size, NULL, 0) < 0) {
  74. warn("sysctl 'KERN_CPTIME':");
  75. return NULL;
  76. }
  77. if (!valid) {
  78. valid = 1;
  79. return NULL;
  80. }
  81. return bprintf("%d%%", 100 *
  82. ((a[CP_USER] + a[CP_NICE] + a[CP_SYS] + a[CP_INTR]) -
  83. (b[CP_USER] + b[CP_NICE] + b[CP_SYS] + b[CP_INTR])) /
  84. ((a[CP_USER] + a[CP_NICE] + a[CP_SYS] + a[CP_INTR] +
  85. a[CP_IDLE]) -
  86. (b[CP_USER] + b[CP_NICE] + b[CP_SYS] + b[CP_INTR] +
  87. b[CP_IDLE])));
  88. }
  89. #endif