要获取Windows系统的各项性能指标并实时保存,可以使用C#编写一个应用程序。以下是一个简单的示例代码,演示如何使用PerformanceCounter类获取系统性能指标,并使用StreamWriter类将数据保存到文件中。
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
class Program
{
static void Main()
{
// 创建性能计数器对象
PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
PerformanceCounter memoryCounter = new PerformanceCounter("Memory", "Available MBytes");
// 创建文件写入器对象
StreamWriter writer = new StreamWriter("performance.log", true);
// 循环获取性能指标并保存到文件中
while (true)
{
float cpuUsage = cpuCounter.NextValue();
float availableMemory = memoryCounter.NextValue();
// 获取当前时间
DateTime currentTime = DateTime.Now;
// 将性能指标写入文件
writer.WriteLine($"[{currentTime}] CPU Usage: {cpuUsage}% Available Memory: {availableMemory}MB");
writer.Flush(); // 立即写入文件
// 休眠1秒
Thread.Sleep(1000);
}
}
}
上述代码创建了两个PerformanceCounter对象,一个用于获取CPU使用率,另一个用于获取可用内存。然后使用StreamWriter对象将数据保存到performance.log文件中。程序会不断循环获取性能指标并保存,每次循环间隔1秒。
你可以根据自己的需求修改代码,添加其他性能指标或调整保存的文件路径和名称。