2014-10-27 50 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);