5

Possible Duplicate:
How to measure how long is a function running?

I'm writing a UDP chat with reliable data transfer. I need to start a timer when a packet is sent, and stop it as soon it receives an answer from the server (ACK - acknowledgment).

Here is my code:

 private void sendButton_Click(object sender, EventArgs e)
 {
     Packet snd = new Packet(ack, textBox1.Text.Trim());
     textBox1.Text = string.Empty;
     Smsg = snd.GetDataStream();//convert message into array of bytes to send.
     while (true)
     {
        try
         {  // Here I need to Start a timer!
           clientSock.SendTo(Smsg, servEP); 
           clientSock.ReceiveFrom(Rmsg, ref servEP);
           //Here I need to stop a timer and get elapsed amount of time.

           Packet rcv = new Packet(Rmsg);
           if (Rmsg != null && rcv.ACK01 != ack)
               continue;

           if (Rmsg != null && rcv.ACK01 == ack)
           {
            this.displayMessageDelegate("ack is received :"+ack);
            ChangeAck(ack);
            break;
           }

Thank you.

Community
  • 1
  • 1
user1886060
  • 53
  • 1
  • 1
  • 5
  • 1
    You most likely do not want a timer. You probably want a `System.Diagnostics.Stopwatch`. – PhoenixReborn Dec 07 '12 at 17:01
  • 1
    If this is entirely synchronous then you don't need a Timer at all, just get DateTime.UtcNow when you start, DateTime.UtcNow when you stop and compute the TimeSpan between. Should be accurate enough. – Lloyd Dec 07 '12 at 17:01
  • 1
    @Lloyd UtcNow only has an apx resolution of 10 ms. – paparazzo Dec 07 '12 at 17:07

2 Answers2

36

Don't use a Timer. It's not usually accurate enough, and there's a simpler object designed for just this work: The Stopwatch class.

Code sample from the MSDN documentation:

using System;
using System.Diagnostics;
using System.Threading;
class Program
{
    static void Main(string[] args)
    {
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
        Thread.Sleep(10000);
        stopWatch.Stop();
        // Get the elapsed time as a TimeSpan value.
        TimeSpan ts = stopWatch.Elapsed;

        // Format and display the TimeSpan value. 
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
        Console.WriteLine("RunTime " + elapsedTime);
    }
}

In your case, you'd start it when the packet is sent, and stop it when the ack is received.

David
  • 72,686
  • 18
  • 132
  • 173
  • Thank you for you answer. Have i question: are there any methods to get microseconds? – user1886060 Dec 07 '12 at 17:39
  • It looks like it can go to milliseconds only. There is an ElapsedTicks property, but there's no documentation on what length of time that is, and how it relates to milliseconds, but that appears to be because it varies based on the environment. There's just a note that it's different than the System.DateTime.Ticks. BUT it says you can use the Frequency to calculate it. http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.frequency.aspx "Gets the frequency of the timer as the number of ticks per second. This field is read-only." – David Dec 07 '12 at 17:49
  • A tick is the standard unit of time in Windows. That's in both .Net and WinAPI. Internally, .Net DateTimes and TImeSpans are stored as a 64 bit integer whose value is the number of ticks since epoch (Midnight on Jan 1, 0001 CE for DateTimes). – Bacon Bits Dec 15 '17 at 18:22
  • [`TimeSpan.TicksPerSecond`](https://learn.microsoft.com/en-us/dotnet/api/system.timespan.tickspersecond?view=netframework-4.7.1) tells you how many ticks are in a second. (It's `1e7`.) There are similar properties for millisecond, minute, hour, and day. This is documented in the [`System.DateTime` documentaion](https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=netframework-4.7.1). – Bacon Bits Dec 15 '17 at 18:22
2

Stopwatch is so much better than any timer for this.

var stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();

// Your code here.

stopwatch.Stop();

And then you can access the Elapsed property (of type TimeSpan) to see the elapsed time.

Honza Brestan
  • 10,637
  • 2
  • 32
  • 43