-2

I have a problem: my performance program always shows 0% CPU Usage...

I Have added 1 label called Text value CPU:

Here is the code:

public partial class Form1 : Form
{
    PerformanceCounter cpu = new PerformanceCounter ("Processor", "% Processor Time", "_Total");

    public Form1()
    {
        InitializeComponent();
        //string cpu_ussage =
        Text.Text = "CPU: " + CPU_TIME();
    }
    // Provjera Procesa koristeći %
    public string CPU_TIME()
    {
        float cpu_time;

        cpu_time = cpu.NextValue();
        return Math.Round(Convert.ToDouble(cpu_time.ToString()), 2) + "%";

    }
    private void timer1_tick(object sender, EventArgs e)
    {
      Text.Text = "CPU Time:" + CPU_TIME();
    }
}
Anton Sizikov
  • 9,105
  • 1
  • 28
  • 39

2 Answers2

0

You can replace with just

return cpu.NextValue();
Bridge
  • 29,818
  • 9
  • 60
  • 82
Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51
0

Could be because the CPU % is being read after the program already runs and completes and this counter is actually 0. I tried you example and it is indeed printing 0. But when you try the following which does it in a loop you will see values.

using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;



namespace Stackoverflow
{
    public class PerfCounters
    {
        public static void Main()
        {
            var processorCategory = PerformanceCounterCategory.GetCategories()
                .FirstOrDefault(cat => cat.CategoryName == "Processor");
            var countersInCategory = processorCategory.GetCounters("_Total");
            DisplayCounter(countersInCategory
                .First(cnt => cnt.CounterName == "% Processor Time"));
            Console.Read();
        }
        private static void DisplayCounter(PerformanceCounter performanceCounter)
        {
            while (!Console.KeyAvailable)
            {
                Console.WriteLine("{0}\t{1} = {2}",
                    performanceCounter.CategoryName
                    , performanceCounter.CounterName
                    , performanceCounter.NextValue());
                Thread.Sleep(1000);
            }
        }
    }
}

HTH

Ash
  • 2,531
  • 2
  • 29
  • 38