代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
C#
】
获得Cpu使用率类
作者:
灏明
/ 发布于
2016/8/26
/
596
using System; using Microsoft.Win32; using System.Diagnostics; using System.Runtime.InteropServices; namespace Discuz.Common { /// <summary> /// SysInfo 的摘要说明。 /// </summary> public class SysInfo { #region CpuUsage类 /// <summary> /// Defines an abstract base class for implementations of CPU usage counters. /// </summary> public abstract class CpuUsage { /// <summary> /// Creates and returns a CpuUsage instance that can be used to query the CPU time on this operating system. /// </summary> /// <returns>An instance of the CpuUsage class.</returns> /// <exception cref="NotSupportedException">This platform is not supported -or- initialization of the CPUUsage object failed.</exception> public static CpuUsage Create() { if (m_CpuUsage == null) { if (Environment.OSVersion.Platform == PlatformID.Win32NT) m_CpuUsage = new CpuUsageNt(); else if (Environment.OSVersion.Platform == PlatformID.Win32Windows) m_CpuUsage = new CpuUsage9x(); else throw new NotSupportedException(); } return m_CpuUsage; } /// <summary> /// Determines the current average CPU load. /// </summary> /// <returns>An integer that holds the CPU load percentage.</returns> /// <exception cref="NotSupportedException">One of the system calls fails. The CPU time can not be obtained.</exception> public abstract int Query(); /// <summary> /// Holds an instance of the CPUUsage class. /// </summary> private static CpuUsage m_CpuUsage= null; } //------------------------------------------- win 9x --------------------------------------- /// <summary> /// Inherits the CPUUsage class and implements the Query method for Windows 9x systems. /// </summary> /// <remarks> /// This class works on Windows 98 and Windows Millenium Edition. /// You should not use this class directly in your code. Use the CPUUsage.Create() method to instantiate a CPUUsage object. /// </remarks> internal sealed class CpuUsage9x : CpuUsage { /// <summary> /// Initializes a new CPUUsage9x instance. /// </summary> /// <exception cref="NotSupportedException">One of the system calls fails.</exception> public CpuUsage9x() { try { // start the counter by reading the value of the 'StartStat' key RegistryKey startKey = Registry.DynData.OpenSubKey(@"PerfStats/StartStat", false); if (startKey == null) throw new NotSupportedException(); startKey.GetValue(@"KERNEL/CPUUsage"); startKey.Close(); // open the counter's value key m_StatData = Registry.DynData.OpenSubKey(@"PerfStats/StatData", false); if (m_StatData == null) throw new NotSupportedException(); } catch (NotSupportedException e) { throw e; } catch (Exception e) { throw new NotSupportedException("Error while querying the system information.", e); } } /// <summary> /// Determines the current average CPU load. /// </summary> /// <returns>An integer that holds the CPU load percentage.</returns> /// <exception cref="NotSupportedException">One of the system calls fails. The CPU time can not be obtained.</exception> public override int Query() { try { return (int)m_StatData.GetValue(@"KERNEL/CPUUsage"); } catch (Exception e) { throw new NotSupportedException("Error while querying the system information.", e); } } /// <summary> /// Closes the allocated resources. /// </summary> ~CpuUsage9x() { try { m_StatData.Close(); } catch {} // stopping the counter try { RegistryKey stopKey = Registry.DynData.OpenSubKey(@"PerfStats/StopStat", false); stopKey.GetValue(@"KERNEL/CPUUsage", false); stopKey.Close(); } catch {} } /// <summary>Holds the registry key that's used to read the CPU load.</summary> private RegistryKey m_StatData; } //------------------------------------------- win nt --------------------------------------- /// <summary> /// Inherits the CPUUsage class and implements the Query method for Windows NT systems. /// </summary> /// <remarks> /// This class works on Windows NT4, Windows 2000, Windows XP, Windows .NET Server and higher. /// You should not use this class directly in your code. Use the CPUUsage.Create() method to instantiate a CPUUsage object. /// </remarks> internal sealed class CpuUsageNt : CpuUsage { /// <summary> /// Initializes a new CpuUsageNt instance. /// </summary> /// <exception cref="NotSupportedException">One of the system calls fails.</exception> public CpuUsageNt() { byte[] timeInfo = new byte[32]; // SYSTEM_TIME_INFORMATION structure byte[] perfInfo = new byte[312]; // SYSTEM_PERFORMANCE_INFORMATION structure byte[] baseInfo = new byte[44]; // SYSTEM_BASIC_INFORMATION structure int ret; // get new system time ret = NtQuerySystemInformation(SYSTEM_TIMEINFORMATION, timeInfo, timeInfo.Length, IntPtr.Zero); if (ret != NO_ERROR) throw new NotSupportedException(); // get new CPU's idle time ret = NtQuerySystemInformation(SYSTEM_PERFORMANCEINFORMATION, perfInfo, perfInfo.Length, IntPtr.Zero); if (ret != NO_ERROR) throw new NotSupportedException(); // get number of processors in the system ret = NtQuerySystemInformation(SYSTEM_BASICINFORMATION, baseInfo, baseInfo.Length, IntPtr.Zero); if (ret != NO_ERROR ) throw new NotSupportedException(); // store new CPU's idle and system time and number of processors oldIdleTime = BitConverter.ToInt64(perfInfo, 0); // SYSTEM_PERFORMANCE_INFORMATION.liIdleTime oldSystemTime = BitConverter.ToInt64(timeInfo, 8); // SYSTEM_TIME_INFORMATION.liKeSystemTime processorCount = baseInfo[40]; } /// <summary> /// Determines the current average CPU load. /// </summary> /// <returns>An integer that holds the CPU load percentage.</returns> /// <exception cref="NotSupportedException">One of the system calls fails. The CPU time can not be obtained.</exception> public override int Query() { byte[] timeInfo = new byte[32]; // SYSTEM_TIME_INFORMATION structure byte[] perfInfo = new byte[312]; // SYSTEM_PERFORMANCE_INFORMATION structure double dbIdleTime, dbSystemTime; int ret; // get new system time ret = NtQuerySystemInformation(SYSTEM_TIMEINFORMATION, timeInfo, timeInfo.Length, IntPtr.Zero); if (ret != NO_ERROR) throw new NotSupportedException(); // get new CPU's idle time ret = NtQuerySystemInformation(SYSTEM_PERFORMANCEINFORMATION, perfInfo, perfInfo.Length, IntPtr.Zero); if (ret != NO_ERROR) throw new NotSupportedException(); // CurrentValue = NewValue - OldValue dbIdleTime = BitConverter.ToInt64(perfInfo, 0) - oldIdleTime; dbSystemTime = BitConverter.ToInt64(timeInfo, 8) - oldSystemTime; // CurrentCpuIdle = IdleTime / SystemTime if (dbSystemTime != 0) dbIdleTime = dbIdleTime / dbSystemTime; // CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors dbIdleTime = 100.0 - dbIdleTime * 100.0 / processorCount + 0.5; // store new CPU's idle and system time oldIdleTime = BitConverter.ToInt64(perfInfo, 0); // SYSTEM_PERFORMANCE_INFORMATION.liIdleTime oldSystemTime = BitConverter.ToInt64(timeInfo, 8); // SYSTEM_TIME_INFORMATION.liKeSystemTime return (int)dbIdleTime; } /// <summary> /// NtQuerySystemInformation is an internal Windows function that retrieves various kinds of system information. /// </summary> /// <param name="dwInfoType">One of the values enumerated in SYSTEM_INFORMATION_CLASS, indicating the kind of system information to be retrieved.</param> /// <param name="lpStructure">Points to a buffer where the requested information is to be returned. The size and structure of this information varies depending on the value of the SystemInformationClass parameter.</param> /// <param name="dwSize">Length of the buffer pointed to by the SystemInformation parameter.</param> /// <param name="returnLength">Optional pointer to a location where the function writes the actual size of the information requested.</param> /// <returns>Returns a success NTSTATUS if successful, and an NTSTATUS error code otherwise.</returns> [DllImport("ntdll", EntryPoint="NtQuerySystemInformation")] private static extern int NtQuerySystemInformation(int dwInfoType, byte[] lpStructure, int dwSize, IntPtr returnLength); /// <summary>Returns the number of processors in the system in a SYSTEM_BASIC_INFORMATION structure.</summary> private const int SYSTEM_BASICINFORMATION = 0; /// <summary>Returns an opaque SYSTEM_PERFORMANCE_INFORMATION structure.</summary> private const int SYSTEM_PERFORMANCEINFORMATION = 2; /// <summary>Returns an opaque SYSTEM_TIMEOFDAY_INFORMATION structure.</summary> private const int SYSTEM_TIMEINFORMATION = 3; /// <summary>The value returned by NtQuerySystemInformation is no error occurred.</summary> private const int NO_ERROR = 0; /// <summary>Holds the old idle time.</summary> private long oldIdleTime; /// <summary>Holds the old system time.</summary> private long oldSystemTime; /// <summary>Holds the number of processors in the system.</summary> private double processorCount; } #endregion /// <summary> /// 获得Cpu使用率 /// </summary> /// <returns>返回使用率</returns> public static int GetCpuUsage() { return CpuUsage.Create().Query(); } } }
试试其它关键字
同语言下
.
C#实现的html内容截取
.
C#动态修改文件夹名称(FSO实现,不移动文件)
.
c# 移动文件或文件夹
.
c#图片添加水印
.
网站后台修改图片尺寸代码
.
处理大图片在缩略图时的展示
.
实现对图片上传的接收
.
去除字符串中的空格,回车,换行符转变成‘;’在按‘
.
按照回车换行符分割字符串
.
文件MD5码 比较,检测文件是否一样
可能有用的
.
C#实现的html内容截取
.
C#动态修改文件夹名称(FSO实现,不移动文件)
.
c# 移动文件或文件夹
.
c#图片添加水印
.
网站后台修改图片尺寸代码
.
处理大图片在缩略图时的展示
.
实现对图片上传的接收
.
去除字符串中的空格,回车,换行符转变成‘;’在按‘
.
按照回车换行符分割字符串
.
文件MD5码 比较,检测文件是否一样
灏明
贡献的其它代码
(
23
)
.
获取目录下的文件数和文件夹数
.
全角转半角 半角转全角 接收文本框的值
.
替换jquer的默认$符号
.
获得Cpu使用率类
.
生成验证码,缩略图,及水印图
.
sql 2005 sql 2008导出数据字典方法
.
FileUpload触发图浏览事件
.
一般图匹配(邻接表形式)
.
掉链图片的替代图片方法
.
遍历m个元素取k个的递归解法
Copyright © 2004 - 2024 dezai.cn. All Rights Reserved
站长博客
粤ICP备13059550号-3