cpu.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /* See LICENSE file for copyright and license details. */
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include "../util.h"
  5. #if defined(__linux__)
  6. #include <inttypes.h>
  7. #include <stdint.h>
  8. const char *
  9. cpu_freq(void)
  10. {
  11. uint64_t freq;
  12. /* in kHz */
  13. if (pscanf("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq",
  14. "%"SCNu64, &freq) != 1) {
  15. return NULL;
  16. }
  17. return fmt_human(freq * 1000, 1000);
  18. }
  19. const char *
  20. cpu_perc(void)
  21. {
  22. static long double a[7];
  23. long double b[7];
  24. memcpy(b, a, sizeof(b));
  25. /* cpu user nice system idle iowait irq softirq */
  26. if (pscanf("/proc/stat", "%*s %Lf %Lf %Lf %Lf %Lf %Lf %Lf",
  27. &a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6]) != 7) {
  28. return NULL;
  29. }
  30. if (b[0] == 0) {
  31. return NULL;
  32. }
  33. return bprintf("%d", (int)(100 *
  34. ((b[0] + b[1] + b[2] + b[5] + b[6]) -
  35. (a[0] + a[1] + a[2] + a[5] + a[6])) /
  36. ((b[0] + b[1] + b[2] + b[3] + b[4] + b[5] + b[6]) -
  37. (a[0] + a[1] + a[2] + a[3] + a[4] + a[5] + a[6]))));
  38. }
  39. #elif defined(__OpenBSD__)
  40. #include <sys/param.h>
  41. #include <sys/sched.h>
  42. #include <sys/sysctl.h>
  43. const char *
  44. cpu_freq(void)
  45. {
  46. int freq, mib[2];
  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((size_t)freq * 1000 * 1000, 1000);
  57. }
  58. const char *
  59. cpu_perc(void)
  60. {
  61. int mib[2];
  62. static long int a[CPUSTATES];
  63. long int 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