4

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.

Kuriyama Mirai
  • 867
  • 5
  • 17
  • 37
  • 4
    System.Diagnostics.Stopwatch. – scheien May 30 '14 at 06:24
  • Like http://stackoverflow.com/a/16376269/447156 – Soner Gönül May 30 '14 at 06:25
  • The current suggestions of `Stopwatch` are good if you're wanting to make changes to the code and just want to measure this one (or a few) methods. If you're unable/unwilling to change code and/or you want to measure all of the methods in the application, you might be looking for a [profiler](http://msdn.microsoft.com/en-us/library/ms182372.aspx) – Damien_The_Unbeliever May 30 '14 at 06:30

4 Answers4

10

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);
scheien
  • 2,457
  • 1
  • 19
  • 22
  • From picking `DateTime.Now` to `Base.Start()` there could be some elapsed ticks. So `EndAt - StartAt` wouldnt result in the exact ticks. What about `StartAt = EndAt - base.Elapsed` inside the `Stop`? This way the `StartAt` would be corrected in the end to match the ticks exactly. – C4d Sep 07 '15 at 14:38
  • @C4ud3x: I guess that would be an option if you need that precision. This is just a basic example of how to extend the `Stopwatch` class. – scheien Sep 07 '15 at 17:00
  • No problem, you are the master here. I just wanted to stay safe my thoughts aint bullshit. But sounds like im ok with my way. Thanks – C4d Sep 08 '15 at 07:42
  • @C4ud3x: You are free to use this sample as you like, and modify it to your requirements. :-) – scheien Sep 08 '15 at 08:40
5

You can use System.Diagnostics.Stopwatch class to achieve this. see the sample

            // Create new stopwatch
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();

            // Begin timing
            stopwatch.Start();

            // Tasks performed by method

            // Stop timing
            stopwatch.Stop();

            Console.WriteLine("Time taken : {0}", stopwatch.Elapsed);
2

I've done it by doing this

var watch = System.Diagnostics.Stopwatch.StartNew();
string startTime = DateTime.Now.ToLongTimeString();

//Insert Code Here

watch.Stop();
string timeEnd = DateTime.Now.ToLongTimeString();

//Time Format
string[] hours = watch.Elapsed.TotalHours.ToString().Split('.');
string[] minutes = watch.Elapsed.TotalMinutes.ToString().Split('.');
string[] seconds = watch.Elapsed.TotalSeconds.ToString().Split('.');
string[] milliseconds = watch.Elapsed.TotalMilliseconds.ToString().Split('.');

MessageBox.Show(hours[0].ToString() + ":" + minutes[0].ToString() + ":" + seconds[0].ToString() + "." + milliseconds[0].ToString());
JumpingJezza
  • 5,498
  • 11
  • 67
  • 106
Kuriyama Mirai
  • 867
  • 5
  • 17
  • 37
1

First, you need to create a stopwatch object.

private readonly Stopwatch stopwatch = new Stopwatch();

Then, your method:

public void MyMethod()
{
    stopwatch.Start();

    // Any other code here.

    stopwatch.Stop();

    //returns longs
    long runningTimeInMs = stopwatch.ElapsedMilliseconds;
}
Community
  • 1
  • 1
Complexity
  • 5,682
  • 6
  • 41
  • 84