C# code 查看指定进程的CPU usage


    namespace mainEnter 
    {
        using System;    
        using System.Collections.Generic;
        using System.Diagnostics;    
        using System.Threading;
        using System.Runtime.InteropServices;
        using System.IO;
        //using System.Diagnostics;

        public class Enter 
        {
            [DllImport("kernel32.dll")]
            extern static short QueryPerformanceCounter(ref long x);
            [DllImport("kernel32.dll")]
            extern static short QueryPerformanceFrequency(ref long x);

            private static int[] PID;
            private static double cpuUsage;
            private static long pkt_new, pkt_old, put_new, put_old;
            private static Process process;
       
            static void Main() 
            {

                string path = @"C:\CPU_Per\test.txt";

                if (!Directory.Exists(Path.GetDirectoryName(path)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                }

                StreamWriter sw = new StreamWriter(path, false);
            
                int coreNum;
                long before = 0;
                long now = 0;
                long kernaltime, usertime;
                long frequency = 0;

                getProcess();

               // counter = new PerformanceCounter("Process","pc_process",false);

                Console.WriteLine("Core num: "+getCoreNum());
                Console.WriteLine("Process num: " + PID.Length);
                foreach(int pid in PID)
                {
                    Console.WriteLine("Test\t"
                        + Process.GetProcessById(pid).ProcessName.ToString() + "\t" +pid); 
               
                }
                Console.WriteLine("Enter the PID of process");
                string pidTempt = Console.ReadLine();
                int selectedPID = Convert.ToInt32(pidTempt);

                process = Process.GetProcessById(selectedPID);
                Console.WriteLine("Process ID:\t" + process.Id + "\tProcess name:\t" + process.ProcessName);

                DateTime currentOld = DateTime.Now;
                int min = currentOld.Minute + 1;
                coreNum = getCoreNum();
                Console.WriteLine("Core num:\t" + coreNum);

                while (DateTime.Now.Minute <= min)
                {               
                    cpuUsage = 0;


                    QueryPerformanceFrequency(ref frequency);
                    //PerformanceCounter counter = new PerformanceCounter();

                    QueryPerformanceCounter(ref before);
                    pkt_old = getKenalTime(process);
                    put_old = getUserTime(process);

                    Thread.Sleep(1000);

                    QueryPerformanceCounter(ref now);
                    pkt_new = getKenalTime(process);
                    put_new = getUserTime(process);
                
                    kernaltime = pkt_new - pkt_old;
                    usertime = put_new - put_old;

                    Console.WriteLine("Before\t" + before + "\t" + "now\t" + now + "frequency\t" + frequency);
                    float timeInterval;
                    if ((now - before)==0)
                    {
                        timeInterval = 1;
                    }
                    else
                    {
                        timeInterval = now - before;
                    }
                    Console.WriteLine("Time Interval"+"\t"+timeInterval+"\t"+timeInterval / frequency);
                    cpuUsage = ((kernaltime + usertime)*100)/(coreNum*(1000*timeInterval/frequency));

                    if (cpuUsage > 100) cpuUsage = 100;
                    if (cpuUsage < 1) cpuUsage = 1;

                    Console.WriteLine(DateTime.Now.ToString()+"\t"+"ProcessName\t"
                        +process.ProcessName+"\tCUP usage is: "+ cpuUsage + "%");
                    sw.WriteLine(DateTime.Now.ToString() + "\t" + "ProcessName\t"
                        + process.ProcessName + "\tCUP usage: " + cpuUsage + "%");
                }
                sw.Close();
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
            }


            private static int[] getProcess()
            {
                Process[] processSet = Process.GetProcessesByName("al_engine"); 
                int num = processSet.Length;
                if(num!=0)
                {
                    PID = new int[num];
                    for (int i = 0; i < num; i++)
                         PID[i] = processSet[i].Id;
                    return PID;
                }
                else
                {
                    PID = new int[]{0};
                    return PID;
                }            
            }

            private static int getCoreNum() 
            {
                int coreNum = 0;
                coreNum = Environment.ProcessorCount;
                return coreNum;
            }

            public static int GetTime(DateTime dt)
            {
                int CatchTime = 0;
                CatchTime = dt.Second * 1000 + dt.Millisecond;
                return CatchTime;
            }

            public static void durationTime()
            {
                //Int64 
            }

            public static long getKenalTime(Process pro)
            {
                return pro.PrivilegedProcessorTime.Milliseconds;
                    //+ (1000 * pro.PrivilegedProcessorTime.Seconds);
            }

            public static long getUserTime(Process pro) 
            {
                return pro.UserProcessorTime.Milliseconds;
                //+(1000 * pro.UserProcessorTime.Seconds);
            }
        }
    }

 

 


[DllImport(
"kernel32.dll")]
extern static short QueryPerformanceCounter(ref long x);
[DllImport(
"kernel32.dll")]
extern static short QueryPerformanceFrequency(ref long x);
这两句是调用http://msdn.microsoft.com/zh-cn/library/3y1sfaz2.aspx
posted @ 2014-04-02 09:01  GAN_REPLACE  阅读(720)  评论(0)    收藏  举报