2014-10-27 102 views
-2

我有這樣的代碼:我該如何計算一小段C#代碼執行需要多長時間?

var userId = Int32.Parse(User.Identity.GetUserId()); 
    using (var context = new IdentityContext()) 
    { 
     roleId = context.Database.SqlQuery<int>("SELECT RoleId FROM AspNetUserRoles where UserId = " + userId).FirstOrDefault(); 
    } 

有一個非常快速和簡單的方式,我可以這個時間需要多長時間來執行。即使在代碼塊之後將答案放入變量中,這足夠了,因爲我可以調試並查看它花了多長時間。

+2

[秒錶](http://msdn.microsoft.com/en-我們/庫/ system.diagnostics.stopwatch%28V = vs.110%29.aspx) – 2014-10-27 13:37:15

回答

3

使用秒錶:後

DateTime start = DateTime.Now; 

和驗證碼:

using System.Diagnostics; 

... 

Stopwatch stopWatch = new Stopwatch(); 

stopWatch.Start(); 

var userId = Int32.Parse(User.Identity.GetUserId()); 
    using (var context = new IdentityContext()) 
    { 
     roleId = context.Database.SqlQuery<int>("SELECT RoleId FROM AspNetUserRoles where UserId = " + userId).FirstOrDefault(); 
    } 

stopWatch.Stop(); 

TimeSpan ts = stopWatch.Elapsed; 

string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",ts.Hours, ts.Minutes, ts.Seconds,ts.Milliseconds/10); 
1

美國可以把這個代碼區域之前

DateTime end = DateTime.Now; 
TimeSpan span = end - start; 

,然後在調試模式下,可以看到span的值;

1

秒錶是你的朋友

// Create new stopwatch 
 
    \t Stopwatch stopwatch = new Stopwatch(); 
 

 
    \t // Begin timing 
 
    \t stopwatch.Start(); 
 

 
    \t // Do something 
 
    \t for (int i = 0; i < 1000; i++) 
 
    \t { 
 
    \t  Thread.Sleep(1); 
 
    \t } 
 

 
    \t // Stop timing 
 
    \t stopwatch.Stop();

1

你有四個選項中,至少。

test project我沒有...

日期時間檢查

DateTime begin = DateTime.UtcNow; 
//what you want to control... 
DateTime end = DateTime.UtcNow; 
Console.WriteLine("DateTime.UtcNow measured time: {0} ms", (end - begin).TotalMilliseconds); 

進度檢查

using System.Diagnostics; 

...

TimeSpan begin = Process.GetCurrentProcess().TotalProcessorTime; 
//what you want to control... 
TimeSpan end = Process.GetCurrentProcess().TotalProcessorTime; 
Console.WriteLine("Process.TotalProcessor measured time: {0} ms", (end - begin).TotalMilliseconds); 

秒錶檢查

using System.Diagnostics; 

...

Stopwatch watch = new Stopwatch(); 
watch.Start(); 
//what you want to control... 
watch.Stop(); 
Console.WriteLine("Stopwatch measured time: {0} ms", watch.ElapsedMilliseconds); 

TickCounter檢查

int start = Environment.TickCount; 
//what you want to control... 
int duration = Environment.TickCount - start; 
Console.WriteLine("TickCount measured time: {0} ms", duration); 
相關問題