如何计算一小段C#代码执行所需的时间

本文关键字:执行 代码 时间 小段 何计算 计算 | 更新日期: 2023-09-27 18:27:54

我有这个代码:

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

有没有一种非常快速简单的方法可以计算执行需要多长时间。即使答案被放入这个代码块之后的变量中,这也足够了,因为我可以调试并查看它花了多长时间。

如何计算一小段C#代码执行所需的时间

使用秒表:

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

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

DateTime start = DateTime.Now;

然后这个代码:

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

然后在调试模式下,您可以看到span的值;

您至少有四个选项。

我做的小测试项目。。。

日期时间检查器

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 Checker

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

秒表是的朋友

    // 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();