Skip to content

Commit

Permalink
CpuUsage for Darwin
Browse files Browse the repository at this point in the history
  • Loading branch information
jhanssen committed Feb 20, 2015
1 parent c4e384f commit bea7d3a
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions rct/CpuUsage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@
#include <mutex>
#include <unistd.h>
#include <assert.h>
#ifdef OS_Darwin
#include <sys/sysctl.h>
#include <sys/types.h>
#include <mach/mach.h>
#include <mach/processor_info.h>
#include <mach/mach_host.h>
#endif

#define SLEEP_TIME 1000000 // one second

Expand All @@ -17,7 +24,7 @@ struct CpuData

float usage;

#ifdef OS_Linux
#if defined(OS_Linux) || defined (OS_Darwin)
float hz;
uint32_t cores;
#endif
Expand All @@ -28,7 +35,7 @@ static std::once_flag sFlag;

static int64_t currentUsage()
{
#ifdef OS_Linux
#if defined(OS_Linux)
FILE* f = fopen("/proc/stat", "r");
if (!f)
return -1;
Expand All @@ -40,6 +47,21 @@ static int64_t currentUsage()
}
fclose(f);
return idle;
#elif defined(OS_Darwin)
processor_info_array_t cpuInfo;
mach_msg_type_number_t numCpuInfo;
natural_t numCPUs = 0;
kern_return_t err = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &numCPUs, &cpuInfo, &numCpuInfo);
if (err == KERN_SUCCESS) {
int64_t usage = 0;
for (unsigned int i = 0; i < numCPUs; ++i) {
usage += cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER] + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE];
}
const size_t cpuInfoSize = sizeof(integer_t) * numCpuInfo;
vm_deallocate(mach_task_self(), (vm_address_t)cpuInfo, cpuInfoSize);
return usage;
}
return -1;
#else
#warning "CpuUsage not implemented for this platform"
return -1;
Expand All @@ -62,7 +84,7 @@ static void collectData()
if (sData.lastUsage > usage) {
sData.usage = 0;
} else {
#ifdef OS_Linux
#if defined(OS_Linux) || defined(OS_Darwin)
const uint32_t deltaUsage = usage - sData.lastUsage;
const uint64_t deltaTime = time - sData.lastTime;
const float timeRatio = deltaTime / (SLEEP_TIME / 1000);
Expand All @@ -85,7 +107,7 @@ float CpuUsage::usage()
sData.usage = 0;
sData.lastUsage = 0;
sData.lastTime = 0;
#ifdef OS_Linux
#if defined(OS_Linux) || defined(OS_Darwin)
sData.hz = sysconf(_SC_CLK_TCK);
sData.cores = sysconf(_SC_NPROCESSORS_ONLN);
#endif
Expand Down

0 comments on commit bea7d3a

Please sign in to comment.