cpu.c 2.2 KB

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