smileymike
smileymike

Reputation: 263

Performance counter C# and HyperPi

I am in attempt to get CPU Usage reading correctly. The code below is executed without problem but I can't get CPU Usage reading at 100% when I run Hyper PI which is a multicores CPU stress test. What did I do wrong? Thank you for your time.

Alternatively, is it possible to get CPU Usage readings from WMI?

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace TestHarnessCPUUsage
{
    class Program
    {
        static void Main(string[] args)
        {
            PerformanceCounter cpuCounter;
            PerformanceCounter ramCounter;

            cpuCounter = new PerformanceCounter();

            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";

            ramCounter = new PerformanceCounter("Memory", "Available MBytes");
            ramCounter.CategoryName = "Memory";
            ramCounter.CounterName = "Available MBytes";

            Console.WriteLine(cpuCounter.NextValue()

+ "%"); Console.WriteLine(ramCounter.NextValue() + "MB");

            Console.ReadKey();
        }


    }
}

Upvotes: 0

Views: 799

Answers (1)

Hans Passant
Hans Passant

Reputation: 941545

That's the kind of perf counter you have to sample yourself. Processor time is a measure over an interval. It tells you how long the processor was turned off, versus it running at 100%. The ratio is the value you get, times 100. One second is the typical interval time, like TaskMgr.exe and Perfmon uses. The smaller you make the interval, the 'noisier' it gets. Down to one sample, like you did, where you get no data at all since there wasn't an interval. Fix:

using System;
using System.Diagnostics;

class Program {
    static void Main(string[] args) {
        PerformanceCounter cpuCounter;
        cpuCounter = new PerformanceCounter();
        cpuCounter.CategoryName = "Processor";
        cpuCounter.CounterName = "% Processor Time";
        cpuCounter.InstanceName = "_Total";
        cpuCounter.NextValue();
        while (!Console.KeyAvailable) {
            System.Threading.Thread.Sleep(1000);
            Console.WriteLine(cpuCounter.NextValue());
        }
    }
}

Upvotes: 1

Related Questions