Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hey guys, I am here again with a problem.
In my program I need to calculate the current CPU usage.

I have searched google and found similar code across multiple websites but it just feels way too complicated for what I need to do AND my CPU never hits 100% usage with this calculation.

Not only does it look too complicated but i do not even understand the code, and when i write a program if i use code i find from google i try to understand it to become a better programmer.

So here is the code i found, if you know a better solution please help me out, and possibly try to explain it, and if there is not a better solution please help me understand this code.

Thank you all!

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;
using ComTypes = System.Runtime.InteropServices.ComTypes;
namespace CPU_PI_Crusher
{
    public class CpuUsage
    {
        //Imports the needed DLL
        [DllImport("kernel32.dll", SetLastError = true)]
        //get needed system file time types
        static extern bool GetSystemTimes(
                    out ComTypes.FILETIME lpIdleTime,
                    out ComTypes.FILETIME lpKernelTime,
                    out ComTypes.FILETIME lpUserTime
                    );
        //Com system information vars
        ComTypes.FILETIME prevSysKernel;
        ComTypes.FILETIME prevSysUser;
        //Time span needed later on
        TimeSpan prevProcTotal;
        //time of last run
        DateTime lastRun;
        //integer object
        Int16 int16CpuUsage;
        
        //Run Count
        long longRunCount;
        /// <summary>
        /// Initilize and define all the variables above
        /// </summary>
        public CpuUsage()
        {
            int16CpuUsage = -1;
            lastRun = DateTime.MinValue;
            prevSysUser.dwHighDateTime = prevSysUser.dwLowDateTime = 0;
            prevSysKernel.dwHighDateTime = prevSysKernel.dwLowDateTime = 0;
            prevProcTotal = TimeSpan.MinValue;
            longRunCount = 0;
        }
        /// <summary>
        /// Gets the CPU Usage and return a short
        /// </summary>
        /// <returns></returns>
        public short GetUsage()
        {
            short cpuCopy = int16CpuUsage;
            if (Interlocked.Increment(ref longRunCount) == 1)
            {
                //Detect if enough time has passed
                if (!EnoughTimePassed)
                {
                    //Decrease run count
                    Interlocked.Decrement(ref longRunCount);
                    return cpuCopy;
                }
                //Define system variables
                ComTypes.FILETIME sysIdle, sysKernel, sysUser;
                TimeSpan procTime;
                //Get current process
                Process process = Process.GetCurrentProcess();
                //Timespan is the CPU time
                procTime = process.TotalProcessorTime;
                //Get the system times of the system variables
                if (!GetSystemTimes(out sysIdle, out sysKernel, out sysUser))
                {
                    Interlocked.Decrement(ref longRunCount); //decrease run count
                    return cpuCopy;
                }
                //If not the first run
                if (!IsFirstRun)
                {
                    UInt64 sysKernelDiff = SubtractTimes(sysKernel, prevSysKernel); //Gets time difference
                    UInt64 sysUserDiff = SubtractTimes(sysUser, prevSysUser); //Gets time difference
                    UInt64 sysTotal = sysKernelDiff + sysUserDiff; //total time
                    Int64 procTotal = procTime.Ticks - prevProcTotal.Ticks; //Total CPU ticks
                    //Usage greate than 0
                    if (sysTotal > 0)
                    {
                        int16CpuUsage = (short)((100.0 * procTotal) / sysTotal); //calculate usage
                    }
                }
                //Define system variables
                prevProcTotal = procTime;
                prevSysKernel = sysKernel;
                prevSysUser = sysUser;
                lastRun = DateTime.Now; //Get the current time
                cpuCopy = int16CpuUsage;
            }
            //decrease the current run time
            Interlocked.Decrement(ref longRunCount);
            //return  cpu usage
            return cpuCopy;
        }
        /// <summary>
        /// Subtract from two com type file times
        /// </summary>
        private UInt64 SubtractTimes(ComTypes.FILETIME a, ComTypes.FILETIME b)
        {
            UInt64 aInt = ((UInt64)(a.dwHighDateTime << 32)) | (UInt64)a.dwLowDateTime;
            UInt64 bInt = ((UInt64)(b.dwHighDateTime << 32)) | (UInt64)b.dwLowDateTime;
            return aInt - bInt;
        }
        /// <summary>
        /// Detect if enough time is passed
        /// </summary>
        private bool EnoughTimePassed
        {
            get
            {
                const int minimumElapsedMS = 250; //Predefined time elspase
                TimeSpan sinceLast = DateTime.Now - lastRun; //Gets the timspan between two datetimes
                return sinceLast.TotalMilliseconds > minimumElapsedMS; //calculate time from the timespan
            }
        }
        /// <summary>
        /// Getter for the FirstRun Object
        /// </summary>
        private bool IsFirstRun
        {
            get
            {
                return (lastRun == DateTime.MinValue);
            }
        }
    }
}
Posted
Updated 18-Jun-11 12:15pm
v2
Comments
Sergey Alexandrovich Kryukov 18-Jun-11 18:19pm    
Isn't it better to provide a Web link instead of the copy of the work? You did not even give a credit to the author...
--SA

1 solution

Have a look at this link.[^]
 
Share this answer
 
Comments
thexcodec 19-Jun-11 22:28pm    
Sure that links works mate?
"Oops! Google Chrome could not connect to zamov.online.fr"
Dr.Walt Fair, PE 19-Jun-11 22:31pm    
The link works for me in Firefox.
thexcodec 20-Jun-11 12:42pm    
ya it works now. Server prob was down for a second or too. The code in the example you gave me looks a lot smaller and i understand it! ill test it and see if it works.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900