|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionA common diagnostic task is to measure the performance of your code. To do that, the .NET Framework offers the The ExecutionStopwatch vs .NET StopwatchThe .NET Framework already contains a time measuring mechanism that could be found in the The DemonstrationIn order to demonstrate the difference in the behavior between the .NET's original class Program
{
static void Main()
{
Stopwatch regularSW = new Stopwatch();
ExecutionStopwatch executionSW = new ExecutionStopwatch();
regularSW.Start();
executionSW.Start();
// the thread won't be executed for 5 seconds
Thread.Sleep(5000);
regularSW.Stop();
executionSW.Stop();
Console.WriteLine("Regular Stopwatch: {0}", regularSW.Elapsed);
Console.WriteLine("Execution Stopwatch: {0}", executionSW.Elapsed);
// Output:
// Regular Stopwatch: 00:00:04.9900562
// Execution Stopwatch: 00:00:00
}
}
The difference can be noticed immediately. While the .NET Source Codeusing System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace DiagnosticsUtils
{
public class ExecutionStopwatch
{
[DllImport("kernel32.dll")]
private static extern long GetThreadTimes
(IntPtr threadHandle, out long createionTime,
out long exitTime, out long kernelTime, out long userTime);
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentThread();
private long m_endTimeStamp;
private long m_startTimeStamp;
private bool m_isRunning;
public void Start()
{
m_isRunning = true;
long timestamp = GetThreadTimes();
m_startTimeStamp = timestamp;
}
public void Stop()
{
m_isRunning = false;
long timestamp = GetThreadTimes();
m_endTimeStamp = timestamp;
}
public void Reset()
{
m_startTimeStamp = 0;
m_endTimeStamp = 0;
}
public TimeSpan Elapsed
{
get
{
long elapsed = m_endTimeStamp - m_startTimeStamp;
TimeSpan result =
TimeSpan.FromMilliseconds(elapsed / 10000);
return result;
}
}
public bool IsRunning
{
get { return m_isRunning; }
}
private long GetThreadTimes()
{
IntPtr threadHandle = GetCurrentThread();
long notIntersting;
long kernelTime, userTime;
long retcode = GetThreadTimes
(threadHandle, out notIntersting,
out notIntersting, out kernelTime, out userTime);
bool success = Convert.ToBoolean(retcode);
if (!success)
throw new Exception(string.Format
("failed to get timestamp. error code: {0}",
retcode));
long result = kernelTime + userTime;
return result;
}
}
}
History
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||