코드 실행 시간 측정
테스트 목적으로 절차/기능/주문이 완료되는 데 얼마나 시간이 걸리는지 알고 싶습니다.
이것은 내가 한 일이지만 내 방법이 잘못되었습니다. 왜냐하면 초의 차이가 0이면 경과된 밀리초를 반환할 수 없기 때문입니다.
sleep 값은 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)
더 나은 방법은 스톱워치를 사용하는 것입니다.DateTime
차이점.
경과 시간을 정확하게 측정하는 데 사용할 수 있는 일련의 메서드 및 속성을 제공합니다.
// create and start a Stopwatch instance
Stopwatch stopwatch = Stopwatch.StartNew();
// replace with your sample code:
System.Threading.Thread.Sleep(500);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
Stopwatch
경과 시간을 측정합니다.
// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();
// Begin timing
stopwatch.Start();
Threading.Thread.Sleep(500)
// Stop timing
stopwatch.Stop();
Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
여기 있습니다.
다음 Stopwatch 래퍼를 사용할 수 있습니다.
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
Stopwatch 클래스를 사용하는 경우 를 사용할 수 있습니다.StartNew() 메서드를 사용하여 시계를 0으로 재설정합니다.그러니까 전화 안 해도 돼요.재설정() 후에 를 누릅니다.시작().도움이 될 수도 있습니다.
연결된 스레드가 응용프로그램 내부에서 코드를 실행하는 데 소요된 시간을 찾고 있는 경우.
사용할 수 있습니다.ProcessThread.UserProcessorTime
당신이 받을 수 있는 재산.System.Diagnostics
네임스페이스입니다.
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
참고: 다중 스레드를 사용하는 경우 각 스레드의 시간을 개별적으로 계산하고 합계하여 총 기간을 계산할 수 있습니다.
Stopwatch는 이 목적을 위해 설계되었으며 에서 실행 시간을 측정하는 가장 좋은 방법 중 하나입니다.그물.
var watch = System.Diagnostics.Stopwatch.StartNew();
/* the code that you want to measure comes here */
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
DateTimes를 사용하여 에서 실행 시간을 측정하지 마십시오.그물.
VB에서 Stopwatch 클래스를 사용하는 방법에 대한 예입니다.NET.
Dim Stopwatch As New Stopwatch
Stopwatch.Start()
''// Test Code
Stopwatch.Stop()
Console.WriteLine(Stopwatch.Elapsed.ToString)
Stopwatch.Restart()
''// Test Again
Stopwatch.Stop()
Console.WriteLine(Stopwatch.Elapsed.ToString)
언급URL : https://stackoverflow.com/questions/16376191/measuring-code-execution-time
'programing' 카테고리의 다른 글
iPad 및 iPhone용 스타일 입력 버튼 (0) | 2023.05.17 |
---|---|
이미지 URI 소스 및 데이터 바인딩 (0) | 2023.05.17 |
Web Configuration Manager와 Configuration Manager의 차이점은 무엇입니까? (0) | 2023.05.12 |
테이블 없이 하드코드된 값 선택 (0) | 2023.05.12 |
셀 형식 반올림 및 소수점 두 자리 표시 (0) | 2023.05.12 |