|
1 | 1 | #include "detection/cpuusage/cpuusage.h" |
| 2 | +#include "util/mallocHelper.h" |
2 | 3 |
|
3 | 4 | #include <sys/types.h> |
4 | | -#include <sys/user.h> |
5 | 5 | #include <sys/sysctl.h> |
| 6 | +#include <sys/resource.h> |
| 7 | +#include <stdlib.h> |
6 | 8 |
|
7 | 9 | const char* ffGetCpuUsageInfo(uint64_t* inUseAll, uint64_t* totalAll) |
8 | 10 | { |
9 | | - // interrupt processing, user processes, system processing, lock spinning, and idling |
10 | | - uint64_t cpTime[5]; |
11 | | - size_t neededLength = sizeof(cpTime); |
12 | | - if(sysctlbyname("kern.cp_time", cpTime, &neededLength, NULL, 0) != 0) |
13 | | - return "sysctlbyname(kern.cp_time) failed"; |
| 11 | + size_t neededLength = 0; |
| 12 | + if(sysctlbyname("kern.cp_times", NULL, &neededLength, NULL, 0) != 0) |
| 13 | + return "sysctlbyname(kern.cp_times, NULL) failed"; |
14 | 14 |
|
15 | | - *inUseAll = cpTime[0] + cpTime[1] + cpTime[2] + cpTime[3]; |
16 | | - *totalAll = *inUseAll + cpTime[4]; |
| 15 | + uint32_t coreCount = neededLength / (CPUSTATES * sizeof(uint64_t)); |
| 16 | + assert(coreCount > 0); |
| 17 | + |
| 18 | + FF_AUTO_FREE uint64_t (*cpTimes)[CPUSTATES] = malloc(neededLength); |
| 19 | + if(sysctlbyname("kern.cp_times", cpTimes, &neededLength, NULL, 0) != 0) |
| 20 | + return "sysctlbyname(kern.cp_times, cpTime) failed"; |
| 21 | + |
| 22 | + for (uint32_t i = 0; i < coreCount; ++i) |
| 23 | + { |
| 24 | + uint64_t* cpTime = cpTimes[i]; |
| 25 | + uint64_t inUse = cpTime[CP_USER] + cpTime[CP_NICE] + cpTime[CP_SYS]; |
| 26 | + uint64_t total = cpTime[CP_INTR] + cpTime[CP_IDLE]; |
| 27 | + *inUseAll += inUse; |
| 28 | + *totalAll += total; |
| 29 | + } |
17 | 30 |
|
18 | 31 | return NULL; |
19 | 32 | } |
0 commit comments