VB.NET 在 Windows下通过WIn32API获取CPU和内存的使用率
.net 要获取CPU和内存的使用率,一般是通过 PerformanceCounter 或者 WMI 查询得到,但是如果操作系统经常不正常断电或者别的什么原因,让系统的性能计数器抽风了,可能就会造成初始化 PerformanceCounter 对象出错。
性能计数器错误一般可以通过 lodctr /r 可以修复,但是时不时要这么搞一下,对用户总是太不友好了,所以能通过 Win32API 来获取也是一个不错的选项。
代码已封装到两个工具类 CpuUsageNt 和 MemUsage 里面了

''' <summary>
''' Inherits the CPUUsage class and implements the Query method for Windows NT systems.
''' </summary>
''' <remarks>
''' <p>This class works on Windows NT4, Windows 2000, Windows XP, Windows .NET Server and higher.</p>
''' </remarks>
Private NotInheritable Class CpuUsageNt
''' <summary>
''' Initializes a new CpuUsageNt instance.
''' </summary>
''' <exception cref="NotSupportedException">One of the system calls fails.</exception>
Public Sub New()
Dim timeInfo(31) As Byte ' SYSTEM_TIME_INFORMATION structure
Dim perfInfo(311) As Byte ' SYSTEM_PERFORMANCE_INFORMATION structure
Dim baseInfo(43) As Byte ' SYSTEM_BASIC_INFORMATION structure
Dim ret As Integer If (Environment.OSVersion.Platform <> PlatformID.Win32NT) Then
Throw New NotSupportedException()
End If ' get new system time
ret = NtQuerySystemInformation(SYSTEM_TIMEINFORMATION, timeInfo, timeInfo.Length, IntPtr.Zero)
If ret <> NO_ERROR Then
Throw New NotSupportedException()
End If
' get new CPU's idle time
ret = NtQuerySystemInformation(SYSTEM_PERFORMANCEINFORMATION, perfInfo, perfInfo.Length, IntPtr.Zero)
If ret <> NO_ERROR Then
Throw New NotSupportedException()
End If
' get number of processors in the system
ret = NtQuerySystemInformation(SYSTEM_BASICINFORMATION, baseInfo, baseInfo.Length, IntPtr.Zero)
If ret <> NO_ERROR Then
Throw New NotSupportedException()
End If
' 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)
End Sub ''' <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 Function Query() As Integer
Dim timeInfo(31) As Byte ' SYSTEM_TIME_INFORMATION structure
Dim perfInfo(311) As Byte ' SYSTEM_PERFORMANCE_INFORMATION structure ' get new system time
Dim ret As Integer = NtQuerySystemInformation(SYSTEM_TIMEINFORMATION, timeInfo, timeInfo.Length, IntPtr.Zero)
If ret <> NO_ERROR Then
Throw New NotSupportedException()
End If
' get new CPU's idle time
ret = NtQuerySystemInformation(SYSTEM_PERFORMANCEINFORMATION, perfInfo, perfInfo.Length, IntPtr.Zero)
If ret <> NO_ERROR Then
Throw New NotSupportedException()
End If
' CurrentValue = NewValue - OldValue
Dim dbIdleTime As Double = BitConverter.ToInt64(perfInfo, 0) - _oldIdleTime
Dim dbSystemTime As Double = BitConverter.ToInt64(timeInfo, 8) - _oldSystemTime
' CurrentCpuIdle = IdleTime / SystemTime
If dbSystemTime <> 0 Then
dbIdleTime = dbIdleTime / dbSystemTime
End If
' 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 CInt(Fix(dbIdleTime))
End Function ''' <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 Shared Function NtQuerySystemInformation(ByVal dwInfoType As Integer,
ByVal lpStructure() As Byte,
ByVal dwSize As Integer,
ByVal returnLength As IntPtr) As Integer
End Function ''' <summary>Returns the number of processors in the system in a SYSTEM_BASIC_INFORMATION structure.</summary>
Private Const SYSTEM_BASICINFORMATION As Integer = 0
''' <summary>Returns an opaque SYSTEM_PERFORMANCE_INFORMATION structure.</summary>
Private Const SYSTEM_PERFORMANCEINFORMATION As Integer = 2
''' <summary>Returns an opaque SYSTEM_TIMEOFDAY_INFORMATION structure.</summary>
Private Const SYSTEM_TIMEINFORMATION As Integer = 3
''' <summary>The value returned by NtQuerySystemInformation is no error occurred.</summary>
Private Const NO_ERROR As Integer = 0
''' <summary>Holds the old idle time.</summary>
Private _oldIdleTime As Long
''' <summary>Holds the old system time.</summary>
Private _oldSystemTime As Long
''' <summary>Holds the number of processors in the system.</summary>
Private _processorCount As Double
End Class
CpuUsageNt

1 Private NotInheritable Class MemUsage
2 <StructLayout(LayoutKind.Sequential)>
3 Private Structure MEMORY_INFO
4 ''' <summary>
5 ''' 当前结构体大小
6 ''' </summary>
7 Public dwLength As UInteger
8 ''' <summary>
9 ''' 当前内存使用率
10 ''' </summary>
11 Public dwMemoryLoad As UInteger
12 ''' <summary>
13 ''' 总计物理内存大小
14 ''' </summary>
15 Public dwTotalPhys As UInteger
16 ''' <summary>
17 ''' 可用物理内存大小
18 ''' </summary>
19 Public dwAvailPhys As UInteger
20 ''' <summary>
21 ''' 总计交换文件大小
22 ''' </summary>
23 Public dwTotalPageFile As UInteger
24 ''' <summary>
25 ''' 可用交换文件大小
26 ''' </summary>
27 Public dwAvailPageFile As UInteger
28 ''' <summary>
29 ''' 总计虚拟内存大小
30 ''' </summary>
31 Public dwTotalVirtual As UInteger
32 ''' <summary>
33 ''' 可用虚拟内存大小
34 ''' </summary>
35 Public dwAvailVirtual As UInteger
36 End Structure
37 <DllImport("kernel32")>
38 Private Shared Sub GlobalMemoryStatus(ByRef meminfo As MEMORY_INFO)
39 End Sub
40
41 Public Function Query() As Int32
42 Dim iRet As Int32 = 0
43 Try
44 Dim MemInfo As New MEMORY_INFO
45 GlobalMemoryStatus(MemInfo)
46 iRet = CInt(MemInfo.dwMemoryLoad)
47 Debug.Print("[DEBUG] GlobalMemoryStatus dwMemoryLoad={0}", iRet)
48 Catch ex As Exception
49 Debug.Print("[WARN ] GlobalMemoryStatus Err:{0}", ex.Message)
50 End Try
51 Return iRet
52 End Function
53
54 ''' <summary>
55 ''' 格式化容量大小
56 ''' </summary>
57 ''' <param name="size">容量(B)</param>
58 ''' <returns>已格式化的容量</returns>
59 Private Shared Function FormatSize(ByVal size As Double) As String
60 Dim d As Double = size
61 Dim i As Integer = 0
62 Do While (d > 1024) AndAlso (i < 5)
63 d /= 1024
64 i += 1
65 Loop
66 Dim unit() As String = {"B", "KB", "MB", "GB", "TB"}
67 Return (String.Format("{0} {1}", Math.Round(d, 2), unit(i)))
68 End Function
69 End Class
MemUsage
参考资料
VB.NET 在 Windows下通过WIn32API获取CPU和内存的使用率的更多相关文章
- Linux下使用java获取cpu、内存使用率
原文地址:http://www.voidcn.com/article/p-yehrvmep-uo.html 思路如下:Linux系统中可以用top命令查看进程使用CPU和内存情况,通过Runtime类 ...
- 方法:Linux 下用JAVA获取CPU、内存、磁盘的系统资源信息
CPU使用率: InputStream is = null; InputStreamReader isr = null; BufferedReader brStat = null; StringTok ...
- 获取CPU和内存的使用率
1.获取CPU的使用率 主要就是一个计算. int CUseRate::GetCPUUseRate() //获取CPU使用率 { ; FILETIME ftIdle, ftKernel, ftUser ...
- Linux下查看内核、CPU、内存及各组件版本的命令和方法
Linux下查看内核.CPU.内存及各组件版本的命令和方法 Linux查看内核版本: uname -a more /etc/*release ...
- C# 使用 PerformanceCounter 获取 CPU 和 硬盘的使用率
C# 使用 PerformanceCounter 获取 CPU 和 硬盘的使用率: 先看界面: 建一个 Windows Form 桌面程序,代码如下: using System; using Sys ...
- Golang获取CPU、内存、硬盘使用率
Golang获取CPU.内存.硬盘使用率 工具包 go get github.com/shirou/gopsutil 实现 func GetCpuPercent() float64 { percent ...
- Android获取cpu和内存信息、网址的代码
android获取手机cpu并判断是单核还是多核 /** * Gets the number of cores available in this device, across all proce ...
- Python获取CPU、内存使用率以及网络使用状态代码
Python获取CPU.内存使用率以及网络使用状态代码_python_脚本之家 http://www.jb51.net/article/134714.htm
- Linux下java获取CPU、内存、磁盘IO、网络带宽使用率
一.CPU 使用proc文件系统,"proc文件系统是一个伪文件系统,它只存在内存当中,而不占用外存空间.它以文件系统的方式为访问系统内核数据的操作提供接口.用户和应用程序可以通过proc得 ...
- windows下配置tomcat服务器的jvm内存大小的两种方式
难得遇到一次java堆内存溢出(心里想着,终于可以来一次jvm性能优化了$$) 先看下报错信息, java.lang.OutOfMemoryError: GC overhead limit excee ...
随机推荐
- java开发,入职第一天都干什么,带提前了解
2024.7.24,帝都今晚大雨,在雨声磅礴的夜晚适合干什么,没错适合敲代码,写博客,今晚来聊下入职一个新公司,第一天都干什么. 无论是刚毕业的新手小白,还是工作十余年的职场老人,入职一家新公司,只要 ...
- static个人理解
static解:主要用于内存管理,static关键字的方法不需要new对象就可以直接在同static内进行调用,在其他类中可直接通过类名进行变量的访问.static关键字属于类,不是类的实例.成员分为 ...
- 支付宝退款和结果查询接口简单实现(.Net 7.0)
〇.前言 支付宝对 .Net 的支持还是比较充分的,在每个接口文档中都有关于 C# 语言的示例,这样就大大降低了对接的难度,很容易上手. 官方接口文档地址:退款-alipay.trade.refund ...
- 【Vue2】Router 路由
1.什么是单页面应用程序 单页面应用程序(英文名: Single Page Application)简称SPA, 顾名思义,指的是一个Web网站中只有唯一-的一-个HTML页面, 所有的功能与交互都在 ...
- 【Layui】16 表单元素 Form
文档地址: https://www.layui.com/demo/form.html 表单元素: 1.输入框 2.密码框 3.下拉列表 4.单选框 5.复选框 6.文档域 7.富文本 8.开关 单行输 ...
- 《Python数据可视化之matplotlib实践》 源码 第四篇 扩展 第十章
图 10.1 import matplotlib.pyplot as plt import numpy as np plt.axes([0.1, 0.7, 0.3, 0.3], frameon=Tru ...
- 最新版gym-0.26.2中Atari环境下各游戏在不同模式和困难度下的遍历
相关内容参看前文: 最新版gym-0.26.2下Atari环境的安装以及环境版本v0,v4,v5的说明 =========================================== gym中 ...
- vue中使用better-scroll
1.创建vue-cli3项目 指令 vue create 项目名 2.要想使用better-scroll 需要先引入 better-scroll的插件 这里采用 npm的方式 指令 npm ...
- 树莓派高级开发——“IO口驱动代码的编写“ 包含总线地址、物理_虚拟地址、BCM2835芯片手册知识
微机总线地址 地址总线: 百度百科解释: 地址总线 (Address Bus:又称:位址总线) 属于一种电脑总线 (一部份),是由CPU 或有DMA 能力的单元,用来沟通这些单元想要存取(读取/写入) ...
- Lucas-Washburn + Cassie-Baxter
如果粉末间隙内壁的表面能随着润湿而降低,则液体会向管内上升渗入(\(\gamma_{\text{SL}}<\gamma_{\text{SO}}\)). 考虑液体上升的驱动力来自于附加压力,则由弯 ...