Skip to main content
 首页 » 编程设计

c#之如何计算 C# 中方法的时间

2024年02月06日13webabcd

<分区>

我如何计算 3 种方法的时间,但这只是第一种和最后一种方法我需要时间。我不需要中间方法的时间。 前任。 MethodOne 需要 200 ms,MethodTwo 需要 500 ms,MethodThree 需要 300 ms。总时间:1000 毫秒。但它应该是 1000 ms – 500 ms (MethodTwo) = 500 ms。

有没有什么软件可以做到这一点?或者如何更改我的代码以使其正常工作?

static void Main(string[] args) 
{ 
  Console.WriteLine("============================"); 
  Console.WriteLine("        Performance         "); 
  Console.WriteLine("============================\n"); 
 
  Console.WriteLine("Total time: {0}", TimeTaking(MethodOne).TotalMilliseconds.ToString()); 
  Console.ReadKey(); 
} 
 
static TimeSpan TimeTaking(Action methodName) 
{ 
  Stopwatch stopwatch = Stopwatch.StartNew(); 
  methodName(); 
  stopwatch.Stop(); 
  return stopwatch.Elapsed; 
} 
 
static void MethodOne() 
{ 
  Thread.Sleep(200); 
  MethodTwo(); 
} 
 
static void MethodTwo() 
{ 
  // Stop TimeTaking 
  Thread.Sleep(500); 
  MethodThree(); 
} 
 
static void MethodThree() 
{  
  // continue TimeTaking 
  Thread.Sleep(300);  
}