C# Console Title Running Time
Hello RaGEZONE.
A few minutes ago a friend asked me to make a running time script for C#.
And now I decide to share it.
At the upper add:
PHP Code:
using System.Diagnostics;
Add a new field/property:
PHP Code:
Stopwatch t = new Stopwatch();
Add this method:
PHP Code:
static bool IsDivisble(long x, int n)
{
return (x % n) == 0;
}
In a void, add:
PHP Code:
t = new Stopwatch();
t.Start();
while(t.IsRunning)
{
if (IsDivisble(t.ElapsedMilliseconds, 1000))
{
// READ REST OF TOPIC
}
}
Between the IsDivisble you can change the title. You can do it on two ways:
1. Use properties (t.Elasped.Seconds, t.Elasped.Minutes, t.Elasped.Hours, t.Elasped.Days)
Don't use t.Elasped.TotalSeconds as it is NOT only seconds but some other shit.
For example:
PHP Code:
Console.Title = "Carbon - Runned for " + t.Elasped.Seconds + " second(s), " + t.Elasped.Minutes + " minute(s), " + t.Elasped.Hours + " hour(s), " + t.Elasped.Days + " day(s)";
If you want not 4 seconds but 04 seconds, you can use t.Elasped.ToString("") with a DateTime format.
PHP Code:
t.Elasped.ToString("ss"); // Gives time in seconds with 2 digits, like 05 seconds
t.Elasped.ToString("mm"); // Gives time in minutes with 2 digits, like 08 minutes
t.Elasped.ToString("hh"); // Gives time in hours with 2 digits, like 04 hours, THIS DOES NOT INCLUDE 24 hour clock
t.Elasped.ToString("HH"); // Gives time in hours with 2 digits, like 06 hours, THIS DOES INCLUDE 24 hour clock
For the days I suggest to always use t.Elasped.Days.
To use it, use for example:
PHP Code:
Console.Title = "Carbon - Running for " + t.Elasped.ToString("ss") + " second(s), " + t.Elasped.ToString("mm") + " minute(s) and " + t.Elasped.ToString("HH") + " hour(s)!";
Re: C# Console Title Running Time
Your code eats the CPU... try this:
Code:
public static void Main(string[] args)
{
var stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
using(var timer = new System.Timers.Timer(1000))
{
timer.Elapsed += (sender, e) =>
{
var elapsed = stopWatch.Elapsed;
Console.Title = String.Format("{0} second(s), {1} minute(s), {2} hour(s), {3} day(s)", elapsed.Seconds, elapsed.Minutes, elapsed.Hours, elapsed.Days);
};
timer.Start();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
timer.Stop();
}
}