出于测试目的,我想知道完成一个过程/函数/命令需要多长时间。
这就是我所做的,但我的方法是错误的,因为如果秒的差是0,就不能返回经过的毫秒数:
注意,休眠的值是500ms,所以经过的秒数是0,所以它不能返回毫秒数。
Dim Execution_Start As System.DateTime = System.DateTime.Now
Threading.Thread.Sleep(500)
Dim Execution_End As System.DateTime = System.DateTime.Now
MsgBox(String.Format("H:{0} M:{1} S:{2} MS:{3}", _
DateDiff(DateInterval.Hour, Execution_Start, Execution_End), _
DateDiff(DateInterval.Minute, Execution_Start, Execution_End), _
DateDiff(DateInterval.Second, Execution_Start, Execution_End), _
DateDiff(DateInterval.Second, Execution_Start, Execution_End) * 60))
有人能告诉我一种更好的方法吗?也许可以用TimeSpan
解决方案:
Dim Execution_Start As New Stopwatch
Execution_Start.Start()
Threading.Thread.Sleep(500)
MessageBox.Show("H:" & Execution_Start.Elapsed.Hours & vbNewLine & _
"M:" & Execution_Start.Elapsed.Minutes & vbNewLine & _
"S:" & Execution_Start.Elapsed.Seconds & vbNewLine & _
"MS:" & Execution_Start.Elapsed.Milliseconds & vbNewLine, _
"Code execution time", MessageBoxButtons.OK, MessageBoxIcon.Information)
发布于 2013-05-05 00:08:00
发布于 2016-06-05 17:08:21
你可以使用这个秒表包装器:
public class Benchmark : IDisposable
{
private readonly Stopwatch timer = new Stopwatch();
private readonly string benchmarkName;
public Benchmark(string benchmarkName)
{
this.benchmarkName = benchmarkName;
timer.Start();
}
public void Dispose()
{
timer.Stop();
Console.WriteLine($"{benchmarkName} {timer.Elapsed}");
}
}
用法:
using (var bench = new Benchmark($"Insert {n} records:"))
{
... your code here
}
输出:
Insert 10 records: 00:00:00.0617594
对于高级方案,您可以使用BenchmarkDotNet、Benchmark.It或NBench
发布于 2018-04-16 19:25:09
如果要查找关联线程在应用程序内运行代码所花费的时间,请执行以下操作。
您可以使用System.Diagnostics
名称空间下的ProcessThread.UserProcessorTime
属性。
TimeSpan startTime= Process.GetCurrentProcess().Threads[i].UserProcessorTime; // i being your thread number, make it 0 for main
//Write your function here
TimeSpan duration = Process.GetCurrentProcess().Threads[i].UserProcessorTime.Subtract(startTime);
Console.WriteLine($"Time caluclated by CurrentProcess method: {duration.TotalSeconds}"); // This syntax works only with C# 6.0 and above
注意:如果您使用的是多线程,您可以单独计算每个线程的时间,然后将其相加以计算总时长。
https://stackoverflow.com/questions/16376191
复制相似问题