코드 실행 시간 측정
테스트 목적으로 절차 / 기능 / 주문이 완료되는 데 걸리는 시간을 알고 싶습니다.
이것은 내가 한 일이지만 초 차이가 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)
더 나은 방법은 차이점 대신 Stopwatch 를 사용하는 것 DateTime
입니다.
경과 시간을 정확하게 측정하는 데 사용할 수있는 메서드 및 속성 집합을 제공합니다.
Stopwatch stopwatch = Stopwatch.StartNew(); //creates and start the instance of Stopwatch
//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);
다음은 DEMO
.
이 스톱워치 래퍼를 사용할 수 있습니다.
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
For advanced scenarios, you can use Benchmark.It or NBench
If you use the Stopwatch class, you can use the .StartNew() method to reset the watch to 0. So you don't have to call .Reset() followed by .Start(). Might come in handy.
Stopwatch is designed for this purpose and is one of the best way to measure time execution in .NET.
var watch = System.Diagnostics.Stopwatch.StartNew();
/* the code that you want to measure comes here */
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Do not use DateTimes to measure time execution in .NET.
If you are looking for the amount of time that the associated thread has spent running code inside the application.
You can use ProcessThread.UserProcessorTime
Property which you can get under System.Diagnostics
namespace.
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
Note: If you are using multi threads, you can calculate the time of each thread individually and sum it up for calculating the total duration.
참고URL : https://stackoverflow.com/questions/16376191/measuring-code-execution-time
'program tip' 카테고리의 다른 글
Python에서 base 2에 로그인 (0) | 2020.08.17 |
---|---|
HTML 링크를 통해 SMS 본문 텍스트를 미리 채우는 방법 (0) | 2020.08.17 |
업데이트 후 Android 스튜디오의 리소스 오류 : 리소스를 찾을 수 없음 (0) | 2020.08.17 |
GCD의 동시 대기열과 직렬 대기열 (0) | 2020.08.17 |
키보드가 나타날 때 UIScrollView를 어떻게 스크롤합니까? (0) | 2020.08.17 |