CpuUsage: improve performance

by moving the first `/proc/stat` query earlier
This commit is contained in:
李通洲
2022-09-27 22:06:53 +08:00
parent 5096b4a81d
commit db6ad5a268
8 changed files with 61 additions and 53 deletions
+2 -20
View File
@@ -3,13 +3,13 @@
#include <mach/processor_info.h>
#include <mach/mach_host.h>
#include <unistd.h>
static const char* getCpuUsageInfo(long* inUseAll, long* totalAll)
const char* ffGetCpuUsageInfo(long* inUseAll, long* totalAll)
{
natural_t numCPUs = 0U;
processor_info_array_t cpuInfo;
mach_msg_type_number_t numCpuInfo;
*inUseAll = *totalAll = 0;
if (host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &numCPUs, &cpuInfo, &numCpuInfo) != KERN_SUCCESS)
return "host_processor_info() failed";
@@ -26,21 +26,3 @@ static const char* getCpuUsageInfo(long* inUseAll, long* totalAll)
}
return NULL;
}
const char* ffGetCpuUsagePercent(double* result)
{
long inUseAll1 = 0, totalAll1 = 0;
const char* error = getCpuUsageInfo(&inUseAll1, &totalAll1);
if(error)
return error;
sleep(1);
long inUseAll2 = 0, totalAll2 = 0;
error = getCpuUsageInfo(&inUseAll2, &totalAll2);
if(error)
return error;
*result = (double)(inUseAll2 - inUseAll1) / (double)(totalAll2 - totalAll1) * 100;
return NULL;
}