Skip to content

Instantly share code, notes, and snippets.

@miroslavradojevic
Created June 15, 2018 12:45
Show Gist options
  • Select an option

  • Save miroslavradojevic/7c40c87fed34cd6e67e0cfe32043d017 to your computer and use it in GitHub Desktop.

Select an option

Save miroslavradojevic/7c40c87fed34cd6e67e0cfe32043d017 to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.Threading;
using System.Timers;
namespace TryTiming
{
class Program
{
static void Main(string[] args)
{
//--- Stopwatch example
Stopwatch stopwatch = new Stopwatch();
// Begin timing.
stopwatch.Start();
// Run for roughly 1 second and plot the stopwatch time.
for (int i = 0; i < 1000; i++)
{
Thread.Sleep(1);
Console.SetCursorPosition(0, 0);
Console.Write("Stopwatch: {0} msec", stopwatch.ElapsedMilliseconds);
}
// Stop timing.
stopwatch.Stop();
// Write result.
Console.ForegroundColor = ConsoleColor.Red;
Console.SetCursorPosition(0, 1);
Console.Write("Elapsed: {0} msec", stopwatch.ElapsedMilliseconds);
Console.ResetColor();
stopwatch.Reset();
//--- Timer example
System.Timers.Timer t = new System.Timers.Timer(1500);
t.Elapsed += new ElapsedEventHandler(OnTimerElapsed);
t.Enabled = false; // disabled at the beginning
Console.SetCursorPosition(0, 2);
Console.WriteLine("Press 'a' to exit.");
Console.WriteLine("Press 'q' to disable timer.");
Console.WriteLine("Press 'w' to enable timer.");
Console.SetCursorPosition(0, 0);
while (true) {
ConsoleKey pressedKey = Console.ReadKey(true).Key;
if (pressedKey.Equals(ConsoleKey.A))
{
break;
}
if (pressedKey.Equals(ConsoleKey.Q))
{
Console.SetCursorPosition(0, Console.WindowHeight-2);
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(string.Format("{0,50}", "timer disabled"));
Console.SetCursorPosition(0, 0);
t.Enabled = false;
}
if (pressedKey.Equals(ConsoleKey.W))
{
Console.SetCursorPosition(0, Console.WindowHeight-2);
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(string.Format("{0,50}", "timer enabled " + DateTime.Now));
Console.SetCursorPosition(0,0);
t.Enabled = true;
}
}
}
static void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
Console.SetCursorPosition(0, 5);
Console.Write($"Timer triggered at {DateTime.Now}");
Console.SetCursorPosition(0, 0);
Console.SetCursorPosition(0, Console.WindowHeight - 2);
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(string.Format("{0,50}", "timer disabled"));
Console.SetCursorPosition(0, 0);
((System.Timers.Timer)sender).Enabled = false; // disable the timer after the initial trigger, t.Enabled = false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment