📅  最后修改于: 2023-12-03 15:38:48.016000             🧑  作者: Mango
在开发过程中,我们经常需要查看进程运行的时间。在 C# 中,可以通过 .NET Framework 提供的 PerformanceCounter 类来访问操作系统的性能计数器,以获取进程运行时间等信息。
以下是使用 PerformanceCounter 类来显示进程运行时间的步骤:
using System.Diagnostics;
var process = Process.GetCurrentProcess();
var processName = process.ProcessName;
var performanceCounter = new PerformanceCounter("Process", "Elapsed Time", processName, true);
var processElapsedTime = TimeSpan.FromSeconds(performanceCounter.NextValue());
var elapsedTimeFormatted = string.Format("{0:D2}:{1:D2}:{2:D2}",
processElapsedTime.Hours,
processElapsedTime.Minutes,
processElapsedTime.Seconds);
Console.WriteLine("进程运行时间: {0}", elapsedTimeFormatted);
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
var process = Process.GetCurrentProcess();
var processName = process.ProcessName;
var performanceCounter = new PerformanceCounter("Process", "Elapsed Time", processName, true);
var processElapsedTime = TimeSpan.FromSeconds(performanceCounter.NextValue());
var elapsedTimeFormatted = string.Format("{0:D2}:{1:D2}:{2:D2}",
processElapsedTime.Hours,
processElapsedTime.Minutes,
processElapsedTime.Seconds);
Console.WriteLine("进程运行时间: {0}", elapsedTimeFormatted);
}
}
使用 PerformanceCounter 类来显示进程运行时间是很容易的。通过上述步骤和示例代码,您可以轻松地在 C# 中显示进程运行时间。