Welcome!

Join our community of MMO enthusiasts and game developers! By registering, you'll gain access to discussions on the latest developments in MMO server files and collaborate with like-minded individuals. Join us today and unlock the potential of MMO server development!

Join Today!

C# Console Title Running Time

Custom Title Activated
Loyal Member
Joined
Oct 26, 2012
Messages
2,357
Reaction score
1,086
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:
using System.Diagnostics;

Add a new field/property:
PHP:
Stopwatch t = new Stopwatch();

Add this method:
PHP:
static bool IsDivisble(long x, int n)
        {
            return (x % n) == 0;
        }

In a void, add:

PHP:
            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 poop.

For example:
PHP:
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:
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:
Console.Title = "Carbon - Running for " + t.Elasped.ToString("ss") + " second(s), " + t.Elasped.ToString("mm") + " minute(s) and " + t.Elasped.ToString("HH") + " hour(s)!";
 
Joined
Aug 6, 2005
Messages
552
Reaction score
298
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();
            }
}
 
Back
Top