关于性能:如何计算执行一小段C#代码需要多长时间?

How can I time how long it takes a small block of C# code to execute?

本问题已经有最佳答案,请猛点这里访问。

我有这个代码:

1
2
3
4
5
  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();
  }

有没有一个非常快速和简单的方法,我可以花多长时间来执行。即使在这个代码块之后将答案放入一个变量中,这就足够我调试并查看所花的时间了。


使用秒表:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
2
3
4
DateTime begin = DateTime.UtcNow;
//what you want to control...
DateTime end = DateTime.UtcNow;
Console.WriteLine("DateTime.UtcNow measured time: {0} ms", (end - begin).TotalMilliseconds);

进度检查人

1
using System.Diagnostics;

1
2
3
4
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);

秒表检查器

1
using System.Diagnostics;

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

记时器检查器

1
2
3
4
int start = Environment.TickCount;
//what you want to control...
int duration = Environment.TickCount - start;
Console.WriteLine("TickCount measured time: {0} ms", duration);


秒表是你的朋友

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    // Create new stopwatch
        Stopwatch stopwatch = new Stopwatch();

        // Begin timing
        stopwatch.Start();

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

        // Stop timing
        stopwatch.Stop();


您可以将此代码放在区域之前:

1
DateTime start = DateTime.Now;

下面的代码是:

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

然后在调试模式下,可以看到跨度值;