Kuriyama Mirai Kuriyama Mirai - 2 months ago 22
C# Question

Time duration,time start and time end of a method in C#

how can I record the time duration, time start and time end of a method once it was executed using c#?

for example, I click a button and it will do something. Once it start, I'll get the start time, then when the execution is done, I'll get the time end and also the duration of time it take to finish.

Answer

You can use the Stopwatch, which resides in System.Diagnostics namespace.

This has the features of a normal stopwatch, with Start, Stop, Reset, ElapsedMilliseconds and so forth.

This is great for measuring a specific code block or method. You do however state that you want both start and end time in addition to the duration of execution. You could create a custom stopwatch by inheriting the Stopwatch class and extending it with a couple of DateTime properties.

public class CustomStopwatch : Stopwatch
    {

        public DateTime? StartAt { get; private set; }
        public DateTime? EndAt { get; private set; }


        public void Start()
        {
            StartAt = DateTime.Now;

            base.Start();
        }

        public void Stop()
        {
            EndAt = DateTime.Now;

            base.Stop();
        }

        public void Reset()
        {
            StartAt = null;
            EndAt = null;

            base.Reset();
        }

        public void Restart()
        {
            StartAt = DateTime.Now;
            EndAt = null;

            base.Restart();
        }

    }

And use it like this:

CustomStopwatch sw = new CustomStopwatch();
sw.Start();
Thread.Sleep(2342); // just to use some time, logic would be in here somewhere.
sw.Stop();
Console.WriteLine("Stopwatch elapsed: {0}, StartAt: {1}, EndAt: {2}", sw.ElapsedMilliseconds, sw.StartAt.Value, sw.EndAt.Value);