+ cpu[0].oldused = used;
+ cpu[0].oldtotal = total;
+
+ free(cp_time);
+
+ /* per-core stats */
+ cp_len = CPUSTATES * sizeof(long) * info.cpu_count;
+ cp_time = malloc(cp_len);
+
+ /* on e.g. i386 SMP we may have more values than actual cpus; this will just drop extra values */
+ if (sysctlbyname("kern.cp_times", cp_time, &cp_len, NULL, 0) < 0 && errno != ENOMEM) {
+ fprintf(stderr, "Cannot get kern.cp_times\n");
+ }
+
+ for (i = 0; i < info.cpu_count; i++)
+ {
+ total = 0;
+ for (j = 0; j < CPUSTATES; j++)
+ total += cp_time[i*CPUSTATES + j];
+
+ used = total - cp_time[i*CPUSTATES + CP_IDLE];
+
+ if ((total - cpu[i+1].oldtotal) != 0) {
+ info.cpu_usage[i+1] = ((double) (used - cpu[i+1].oldused)) /
+ (double) (total - cpu[i+1].oldtotal);
+ } else {
+ info.cpu_usage[i+1] = 0;
+ }
+
+ cpu[i+1].oldused = used;
+ cpu[i+1].oldtotal = total;
+ }
+
+ free(cp_time);