Add values of an if and see the total result

2

I have a for that is in Objective-C (I do not have much idea of it) I have the app in Swift. I call the function and everything is perfect but it returns two values when I cut the if statement.

2016-01-20 21:54:46.742 Prueba[3306:926796] Core: 0 Usage: 0.153268
2016-01-20 21:54:55.874 Prueba[3306:926796] Core: 1 Usage: 0.081846

What I want is to add the two values of Core 0 and Core 1 and get the% of the sum.

The code of for :

for(unsigned i = 0U; i < numCPUs; ++i) {
        float inUse, total;
        if(prevCpuInfo) {
            inUse = (
                     (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER]   - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER])
                     + (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM])
                     + (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE]   - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE])
                     );
            total = inUse + (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE] - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE]);
        } else {
            inUse = cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER] + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE];
            total = inUse + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE];
        }

        NSLog(@"Core: %u Usage: %f",i,inUse / total);
    }
    
asked by Bogdan 20.01.2016 в 21:59
source

1 answer

0

To obtain the average use of the whole CPU, that is, the sum of all the cores divided by the number of cores modifies the code such that:

float cpuTotal; // !!!!!!!!!!!!!
for(unsigned i = 0U; i < numCPUs; ++i) {
    float inUse, total;
    if(prevCpuInfo) {
        inUse = (
                 (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER]   - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER])
                 + (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM])
                 + (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE]   - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE])
                 );
        total = inUse + (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE] - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE]);
    } else {
        inUse = cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER] + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE];
        total = inUse + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE];
    }

    cpuTotal += inUse / total; // !!!!!!!!!!!!!

}
NSLog(@"CPU Core usage: %f", cpuTotal / numCPUs); // !!!!!!!!!!!!!

PS: I have marked you the important code

    
answered by 20.01.2016 в 22:24