2012-12-07 28 views
0

可能重複:
How to measure how long is a function running?定時器C#。啓動,停止,並得到調用之間的時間量

我正在寫有可靠的數據傳輸一個UDP聊天。我需要在發送數據包時啓動計時器,並在收到服務器應答後立即停止(ACK - 確認)。

這裏是我的代碼:

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; 
      } 

謝謝。

+1

你的問題是什麼? –

+1

你很可能不想要一個計時器。你可能想要一個'System.Diagnostics.Stopwatch'。 – PhoenixReborn

+1

如果這完全是同步的,那麼你根本不需要定時器,只需在開始時獲取DateTime.UtcNow,在停止並計算TimeSpan之間的TimeTime時使用DateTime.UtcNow。應該足夠準確。 – Lloyd

回答

17

請勿使用計時器。這通常不夠準確,並且有一個更簡單的對象設計用於這項工作:Stopwatch類。從MSDN文檔

代碼示例:

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); 
    } 
} 

在你的情況,你會開始時,它的數據包被髮送,並且在接收到ACK時停止。

+0

謝謝你的回答。我有問題嗎?有什麼方法可以獲得微秒? – user1886060

+0

它看起來像只能達到毫秒。有一個ElapsedTicks屬性,但沒有關於什麼時間長度以及它如何與毫秒相關的文檔,但這似乎是因爲它根據環境而變化。有一點需要注意,它不同於System.DateTime.Ticks。但它說你可以使用頻率來計算它。 http://msdn.microsoft.com/zh-cn/library/system.diagnostics.stopwatch.frequency.aspx「獲取計時器的頻率作爲每秒滴答數,該字段爲只讀。」 – David

+0

刻度是Windows中的標準時間單位。這是在.Net和WinAPI中。在內部,.Net DateTimes和TImeSpans存儲爲一個64位整數,其值是自epoch以來的數量(1月1日午夜,0001 CE日期時間)。 –

2

Stopwatch比任何計時器都要好得多。

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

// Your code here. 

stopwatch.Stop(); 

然後你就可以訪問(的TimeSpan型)Elapsed財產看到經過的時間。

相關問題