5 // Created by Peter Hosey on 2006-06-21.
6 // Copyright 2006 Peter Hosey. All rights reserved.
8 // Modified by Christopher Bowns, starting 2007-1-1.
16 #include <sys/types.h>
19 //sysctl and its parameters
20 #include <sys/sysctl.h>
22 #include <sys/errno.h>
25 @implementation CPUInfo
27 static void getCPUStat (processor_info_array_t cpustat)
29 processor_info_array_t processorInfo;
30 natural_t numProcessors_nobodyCares = 0U;
31 mach_msg_type_number_t numProcessorInfo;
33 kern_return_t err = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &numProcessors_nobodyCares, &processorInfo, &numProcessorInfo);
34 if(err == KERN_SUCCESS) {
35 cpustat = processorInfo;
38 NSLog(@"getCPUStat: failed to get cpu statistics");
42 - (CPUInfo *) initWithCapacity:(unsigned)numItems
49 //We could get the number of processors the same way that we get the CPU usage info, but that allocates memory.
50 /* enum { miblen = 2U };
51 int mib[miblen] = { CTL_HW, HW_NCPU };
52 size_t sizeOfNumCPUs = sizeof(numCPUs);
53 int status = sysctl(mib, miblen,
54 &numCPUs, &sizeOfNumCPUs,
55 */ /*newp*/ // NULL, /*newlen*/ 0U);
57 numCPUs = 1; // TODO we're going to assume one CPU for the moment.
58 // NSLog(@"%s error status, assuming one CPU", _cmd);
64 cpudata = calloc(numItems, sizeof(CPUData));
65 if (cpudata == NULL) {
66 NSLog (@"Failed to allocate buffer for CPUInfo");
71 getCPUStat (lastcpustat);
78 processor_info_array_t cpustat;
82 TODO make this multicore. First, we're gonna need a multicore machine to test it on.
84 // for(unsigned i = 0U; i < numCPUs; ++i) {
87 double inUse, total, user, sys, nice, idle;
88 user = cpustat[CPU_STATE_USER];
89 sys = cpustat[CPU_STATE_SYSTEM];
90 nice = cpustat[CPU_STATE_NICE];
91 idle = cpustat[CPU_STATE_IDLE];
93 inUse = user + sys + nice;
97 NSLog(@"%s in use: %f idle: %f", _cmd, inUse, idle);
100 cpudata[inptr].user = (double)user;
101 cpudata[inptr].sys = (double)sys;
102 cpudata[inptr].nice = (double)nice;
103 cpudata[inptr].idle = (double)idle;
104 lastcpustat = cpustat;
105 if (++inptr >= size) // advance our data ptr
116 - (BOOL)getNext:(CPUDataPtr)ptr
120 *ptr = cpudata[outptr++];
129 - (void)getCurrent:(CPUDataPtr)ptr
131 *ptr = cpudata[inptr ? inptr - 1 : size - 1];
135 - (void)getLast:(CPUDataPtr)ptr
137 *ptr = cpudata[inptr > 1 ? inptr - 2 : size + inptr - 2];