88 lines
2.7 KiB
C#
88 lines
2.7 KiB
C#
//Usage Examples:
|
|
//// Get precise milliseconds since application start
|
|
//long ms = SystemUptimeTimer.ElapsedMilliseconds;
|
|
//
|
|
//// Get system uptime (even counts when PC was sleeping)
|
|
//TimeSpan uptime = SystemUptimeTimer.SystemUptime;
|
|
//Console.WriteLine($"PC has been running for {uptime.Days} days, {uptime.Hours} hours");
|
|
//
|
|
//// Benchmark example
|
|
//long start = SystemUptimeTimer.ElapsedMilliseconds;
|
|
//// ... run some code ...
|
|
//long elapsed = SystemUptimeTimer.ElapsedMilliseconds - start;
|
|
//Key Features:
|
|
//Two Measurement Modes:
|
|
//
|
|
//ElapsedMilliseconds: High-precision timer (μs accuracy) since class initialization
|
|
//
|
|
//SystemUptime: Standard Windows uptime (ms accuracy, counts sleep time)
|
|
|
|
using System;
|
|
using System.Diagnostics;
|
|
using System.Runtime.InteropServices;
|
|
|
|
namespace UPSNet
|
|
{
|
|
/// <summary>
|
|
/// High-precision timer measuring time since system startup
|
|
/// </summary>
|
|
public static class SystemUptimeTimer
|
|
{
|
|
[DllImport("kernel32.dll")]
|
|
private static extern uint GetTickCount();
|
|
|
|
[DllImport("kernel32.dll")]
|
|
private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
|
|
|
|
[DllImport("kernel32.dll")]
|
|
private static extern bool QueryPerformanceFrequency(out long lpFrequency);
|
|
|
|
private static readonly long _frequency;
|
|
private static readonly long _startCount;
|
|
private static readonly Stopwatch _fallbackTimer;
|
|
|
|
static SystemUptimeTimer()
|
|
{
|
|
if (!QueryPerformanceFrequency(out _frequency))
|
|
{
|
|
_frequency = -1;
|
|
_fallbackTimer = Stopwatch.StartNew();
|
|
}
|
|
|
|
QueryPerformanceCounter(out _startCount);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets elapsed milliseconds since system startup
|
|
/// </summary>
|
|
public static long ElapsedMilliseconds
|
|
{
|
|
get
|
|
{
|
|
if (_frequency == -1)
|
|
{
|
|
return _fallbackTimer.ElapsedMilliseconds;
|
|
}
|
|
|
|
long currentCount;
|
|
QueryPerformanceCounter(out currentCount);
|
|
return (1000 * (currentCount - _startCount)) / _frequency;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets elapsed seconds since system startup
|
|
/// </summary>
|
|
public static double ElapsedSeconds {
|
|
get { return ElapsedMilliseconds / 1000.0; }
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets system uptime using native API (works even when PC enters sleep)
|
|
/// </summary>
|
|
public static TimeSpan SystemUptime
|
|
{
|
|
get { return TimeSpan.FromMilliseconds(GetTickCount()); }
|
|
}
|
|
}
|
|
} |