//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 { /// /// High-precision timer measuring time since system startup /// 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); } /// /// Gets elapsed milliseconds since system startup /// public static long ElapsedMilliseconds { get { if (_frequency == -1) { return _fallbackTimer.ElapsedMilliseconds; } long currentCount; QueryPerformanceCounter(out currentCount); return (1000 * (currentCount - _startCount)) / _frequency; } } /// /// Gets elapsed seconds since system startup /// public static double ElapsedSeconds { get { return ElapsedMilliseconds / 1000.0; } } /// /// Gets system uptime using native API (works even when PC enters sleep) /// public static TimeSpan SystemUptime { get { return TimeSpan.FromMilliseconds(GetTickCount()); } } } }