Skip to content

Instantly share code, notes, and snippets.

@DamianEdwards
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DamianEdwards/971c18798ce65316d4cd to your computer and use it in GitHub Desktop.
Save DamianEdwards/971c18798ce65316d4cd to your computer and use it in GitHub Desktop.
See the clock and high frequency timer resolution of your PC from .NET
using System;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press any key to start, press SPACEBAR to pause, press ENTER to end");
Console.ReadKey();
var pauseMre = new ManualResetEventSlim(false);
var endMre = new ManualResetEventSlim();
// 0 = running, 1 = paused, 2 = stopped
long state = 0;
var lastTime = DateTime.UtcNow;
var stopwatch = new Stopwatch();
stopwatch.Start();
ThreadPool.QueueUserWorkItem(_ =>
{
while (true)
{
var currentState = Interlocked.Read(ref state);
if (currentState == 1)
{
Console.WriteLine();
Console.WriteLine("Paused, press any key to continue...");
Console.WriteLine();
pauseMre.Wait();
lastTime = DateTime.UtcNow;
stopwatch.Restart();
}
else if (currentState == 2)
{
endMre.Set();
return;
}
var currentTime = DateTime.UtcNow;
var clockDiff = currentTime - lastTime;
var swDiff = stopwatch.Elapsed;
if (clockDiff.TotalMilliseconds > 0)
{
Console.Write("CLOCK CHANGED! ");
}
Console.WriteLine("Clock diff: {0}ms", clockDiff.TotalMilliseconds);
if (swDiff.TotalMilliseconds > 0)
{
Console.Write("STOPWATCH CHANGED! ");
}
Console.WriteLine("Stopwatch diff: {0}ms", swDiff.TotalMilliseconds);
lastTime = currentTime;
stopwatch.Restart();
}
});
while (true)
{
var key = Console.ReadKey();
if (key.Key == ConsoleKey.Spacebar)
{
// Pause
pauseMre.Reset();
Interlocked.Exchange(ref state, 1);
Console.ReadKey();
Interlocked.Exchange(ref state, 0);
pauseMre.Set();
}
else if (key.Key == ConsoleKey.Enter)
{
// End
Interlocked.Exchange(ref state, 2);
endMre.Wait();
Console.WriteLine();
Console.WriteLine("Cancelled");
Console.WriteLine();
return;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment