<p>I need to find a bottleneck and need to accurately as possible measure time.</p>

<p>Is the following code snippet the best way to measure the performance?</p>

<pre><code>DateTime startTime = DateTime.Now;

// Some execution process

DateTime endTime = DateTime.Now;
TimeSpan totalTimeTaken = endTime.Subtract(startTime);
</code></pre>

[{'answer_id': 28646, 'author': 'jsight', 'author_id': 1432, 'author_profile': 'https://Stackoverflow.com/users/1432', 'pm_score': 4, 'selected': False, 'text': '<p>The <a href="http://cplus.about.com/od/howtodothingsinc/a/timing.htm" rel="noreferrer">stopwatch</a> functionality would be better (higher precision).  I\'d also recommend just downloading one of the popular profilers, though (<a href="http://www.jetbrains.com/profiler/" rel="noreferrer">DotTrace</a> and <a href="http://www.red-gate.com/products/ants_profiler/index.htm" rel="noreferrer">ANTS</a> are the ones I\'ve used the most... the free trial for DotTrace is fully functional and doesn\'t nag like some of the others).</p>\n'}, {'answer_id': 28648, 'author': 'Markus Olsson', 'author_id': 2114, 'author_profile': 'https://Stackoverflow.com/users/2114', 'pm_score': 10, 'selected': True, 'text': '<p>No, it\'s not. Use the <a href="http://msdn2.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx" rel="noreferrer">Stopwatch</a> (in <code>System.Diagnostics</code>)</p>\n\n<pre><code>Stopwatch sw = Stopwatch.StartNew();\nPerformWork();\nsw.Stop();\n\nConsole.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds);\n</code></pre>\n\n<p>Stopwatch automatically checks for the existence of high-precision timers.</p>\n\n<p>It is worth mentioning that <code>DateTime.Now</code> often is quite a bit slower than <code>DateTime.UtcNow</code> due to the work that has to be done with timezones, <a href="http://en.wikipedia.org/wiki/Daylight_saving_time" rel="noreferrer">DST</a> and such.</p>\n\n<p>DateTime.UtcNow typically has a resolution of 15&nbsp;ms. See <a href="http://jaychapman.blogspot.com/2007/12/datetimenow-precision-issues-enter.html" rel="noreferrer">John Chapman\'s blog post</a> about <code>DateTime.Now</code> precision for a great summary.</p>\n\n<p>Interesting trivia: The stopwatch falls back on <code>DateTime.UtcNow</code> if your hardware doesn\'t support a high frequency counter. You can check to see if Stopwatch uses hardware to achieve high precision by looking at the static field <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.ishighresolution.aspx" rel="noreferrer">Stopwatch.IsHighResolution</a>.</p>\n'}, {'answer_id': 28649, 'author': 'rp.', 'author_id': 2536, 'author_profile': 'https://Stackoverflow.com/users/2536', 'pm_score': 4, 'selected': False, 'text': '<p>Use the System.Diagnostics.Stopwatch class. </p>\n\n<pre><code>Stopwatch sw = new Stopwatch();\nsw.Start();\n\n// Do some code.\n\nsw.Stop();\n\n// sw.ElapsedMilliseconds = the time your "do some code" took.\n</code></pre>\n'}, {'answer_id': 28653, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve done very little of this sort of performance checking (I tend to just think &quot;this is slow, make it faster&quot;) so I have pretty much always gone with this.</p>\n<p>A google does reveal a lot of resources/articles for performance checking.</p>\n<p>Many mention using pinvoke to get performance information. A lot of the materials I study only really mention using perfmon..</p>\n<h3>Edit:</h3>\n<p>Seen the talks of StopWatch.. Nice! I have learned something :)</p>\n<p><a href="http://www.blackwasp.co.uk/SpeedTestWithStopwatch.aspx" rel="nofollow noreferrer">This looks like a good article</a></p>\n'}, {'answer_id': 28657, 'author': 'mmcdole', 'author_id': 2635, 'author_profile': 'https://Stackoverflow.com/users/2635', 'pm_score': 7, 'selected': False, 'text': '<p>If you want something quick and dirty I would suggest using Stopwatch instead for a greater degree of precision.  </p>\n\n<pre><code>Stopwatch sw = new Stopwatch();\nsw.Start();\n// Do Work\nsw.Stop();\n\nConsole.WriteLine("Elapsed time: {0}", sw.Elapsed.TotalMilliseconds);\n</code></pre>\n\n<p>Alternatively, if you need something a little more sophisticated you should probably consider using a 3rd party profiler such as <a href="http://www.red-gate.com/products/ants_profiler/index.htm" rel="noreferrer">ANTS</a>.</p>\n'}, {'answer_id': 28674, 'author': 'Adam Haile', 'author_id': 194, 'author_profile': 'https://Stackoverflow.com/users/194', 'pm_score': 3, 'selected': False, 'text': '<p>@<a href="https://stackoverflow.com/questions/28637/c-is-datetimenow-the-best-way-to-measure-a-functions-preformance#28656">Sean Chambers</a></p>\n\n<p>FYI, the .NET Timer class is not for diagnostics, it generates events at a preset interval, like this (from <a href="http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx" rel="nofollow noreferrer">MSDN</a>):</p>\n\n<pre><code>System.Timers.Timer aTimer;\npublic static void Main()\n{\n    // Create a timer with a ten second interval.\n    aTimer = new System.Timers.Timer(10000);\n\n    // Hook up the Elapsed event for the timer.\n    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);\n\n    // Set the Interval to 2 seconds (2000 milliseconds).\n    aTimer.Interval = 2000;\n    aTimer.Enabled = true;\n\n    Console.WriteLine("Press the Enter key to exit the program.");\n    Console.ReadLine();\n}\n\n// Specify what you want to happen when the Elapsed event is \n// raised.\nprivate static void OnTimedEvent(object source, ElapsedEventArgs e)\n{\n    Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);\n}\n</code></pre>\n\n<p>So this really doesn\'t help you know how long something took, just that a certain amount of time has passed.</p>\n\n<p>The timer is also exposed as a control in System.Windows.Forms... you can find it in your designer tool box in VS05/VS08</p>\n'}, {'answer_id': 35984, 'author': 'Andrei Rînea', 'author_id': 1796, 'author_profile': 'https://Stackoverflow.com/users/1796', 'pm_score': 4, 'selected': False, 'text': '<p>Ditto Stopwatch, it is way better.</p>\n\n<p>Regarding performance measuring you should also check whether your "// Some Execution Process" is a very short process.</p>\n\n<p>Also bear in mind that the first run of your "// Some Execution Process" might be way slower than subsequent runs.</p>\n\n<p>I typically test a method by running it 1000 times or 1000000 times in a loop and I get much more accurate data than running it once.</p>\n'}, {'answer_id': 39798, 'author': 'Anthony Mastrean', 'author_id': 3619, 'author_profile': 'https://Stackoverflow.com/users/3619', 'pm_score': 4, 'selected': False, 'text': "<p>It's useful to push your benchmarking code into a utility class/method. The <code>StopWatch</code> class does not need to be <code>Disposed</code> or <code>Stopped</code> on error.  So, the simplest code to <em>time</em> some <em>action</em> is</p>\n\n<pre><code>public partial class With\n{\n    public static long Benchmark(Action action)\n    {\n        var stopwatch = Stopwatch.StartNew();\n        action();\n        stopwatch.Stop();\n        return stopwatch.ElapsedMilliseconds;\n    }\n}\n</code></pre>\n\n<p>Sample calling code</p>\n\n<pre><code>public void Execute(Action action)\n{\n    var time = With.Benchmark(action);\n    log.DebugFormat(“Did action in {0} ms.”, time);\n}\n</code></pre>\n\n<p>Here is the extension method version</p>\n\n<pre><code>public static class Extensions\n{\n    public static long Benchmark(this Action action)\n    {\n        return With.Benchmark(action);\n    }\n}\n</code></pre>\n\n<p>And sample calling code</p>\n\n<pre><code>public void Execute(Action action)\n{\n    var time = action.Benchmark()\n    log.DebugFormat(“Did action in {0} ms.”, time);\n}\n</code></pre>\n"}, {'answer_id': 184906, 'author': 'OwenP', 'author_id': 2547, 'author_profile': 'https://Stackoverflow.com/users/2547', 'pm_score': 3, 'selected': False, 'text': '<p>I just found a post in Vance Morrison\'s blog about <a href="http://blogs.msdn.com/vancem/archive/2006/10/01/779503.aspx" rel="noreferrer">a CodeTimer class</a> he wrote that makes using <code>StopWatch</code> easier and does some neat stuff on the side.</p>\n'}, {'answer_id': 236305, 'author': 'Iain', 'author_id': 5993, 'author_profile': 'https://Stackoverflow.com/users/5993', 'pm_score': 3, 'selected': False, 'text': '<p><em>Visual Studio Team System</em> has some features that may help with this problem. Essentially you can write unit tests and mix them in different scenarios to run against your software as part of a stress or load test. This may help to identify areas of code that impact your applications performance the most.</p>\n\n<p>Microsoft\' Patterns and Practices group has some guidance in <em><a href="http://www.codeplex.com/PerfTesting/Wiki/View.aspx?title=Visual%20Studio%20Team%20System%202005%20Index&amp;referringTitle=Home" rel="nofollow noreferrer">Visual Studio Team System Performance Testing Guidance</a></em>.</p>\n'}, {'answer_id': 485044, 'author': 'Mike Dunlavey', 'author_id': 23771, 'author_profile': 'https://Stackoverflow.com/users/23771', 'pm_score': 3, 'selected': False, 'text': '<p>These are all great ways to measure time, but that is only a very indirect way to find bottleneck(s).</p>\n\n<p>The most direct way to find a bottneck in a thread is to get it running, and while it is doing whatever makes you wait, halt it with a pause or break key. Do this several times. If your bottleneck takes X% of time, X% is the probability that you will catch it in the act on each snapshot.</p>\n\n<p><a href="https://stackoverflow.com/questions/375913#378024">Here\'s a more complete explanation of how and why it works</a></p>\n'}, {'answer_id': 5211719, 'author': 'jiya jain', 'author_id': 647090, 'author_profile': 'https://Stackoverflow.com/users/647090', 'pm_score': 3, 'selected': False, 'text': '<p>This is the correct way:</p>\n\n<pre><code>using System;\nusing System.Diagnostics;\n\nclass Program\n{\n    public static void Main()\n    {\n        Stopwatch stopWatch = Stopwatch.StartNew();\n\n            // some other code\n\n        stopWatch.Stop();\n\n        // this not correct to get full timer resolution\n        Console.WriteLine("{0} ms", stopWatch.ElapsedMilliseconds);\n\n        // Correct way to get accurate high precision timing\n        Console.WriteLine("{0} ms", stopWatch.Elapsed.TotalMilliseconds);\n    }\n}\n</code></pre>\n\n<p>For more information go through <em><a href="http://www.totaldotnet.com/Article/ShowArticle59_StopwatchAdvantage.aspx" rel="noreferrer">Use Stopwatch instead of DataTime for getting accurate performance counter</a></em>.</p>\n'}, {'answer_id': 6986472, 'author': 'Valentin Kuzub', 'author_id': 514382, 'author_profile': 'https://Stackoverflow.com/users/514382', 'pm_score': 6, 'selected': False, 'text': '<p><a href="http://dotnet.dzone.com/news/darkness-behind-datetimenow" rel="noreferrer">This article</a> says that first of all you need to compare three alternatives, <code>Stopwatch</code>, <code>DateTime.Now</code> AND <code>DateTime.UtcNow</code>.</p>\n\n<p>It also shows that in some cases (when performance counter doesn\'t exist) Stopwatch is using DateTime.UtcNow + some extra processing. Because of that it\'s obvious that in that case DateTime.UtcNow is the best option (because other use it + some processing)</p>\n\n<p>However, as it turns out, the counter almost always exists - see <em><a href="https://stackoverflow.com/questions/6986701">Explanation about high-resolution performance counter and its existence related to .NET Stopwatch?</a></em>.</p>\n\n<p>Here is a performance graph. Notice how low performance cost UtcNow has compared to alternatives:</p>\n\n<p><img src="https://i.stack.imgur.com/wDhVl.png" alt="Enter image description here"></p>\n\n<p>The X axis is sample data size, and the Y axis is the relative time of the example.</p>\n\n<p>One thing <code>Stopwatch</code> is better at is that it provides higher resolution time measurements. Another is its more OO nature. However, creating an OO wrapper around <code>UtcNow</code> can\'t be hard.</p>\n'}, {'answer_id': 24822240, 'author': 'Blackvault', 'author_id': 3602240, 'author_profile': 'https://Stackoverflow.com/users/3602240', 'pm_score': 3, 'selected': False, 'text': '<p>The way I use within my programs is using the StopWatch class as shown here.</p>\n\n<pre><code>Stopwatch sw = new Stopwatch();\nsw.Start();\n\n\n// Critical lines of code\n\nlong elapsedMs = sw.Elapsed.TotalMilliseconds;\n</code></pre>\n'}, {'answer_id': 25836121, 'author': 'Bye StackOverflow', 'author_id': 4039900, 'author_profile': 'https://Stackoverflow.com/users/4039900', 'pm_score': 2, 'selected': False, 'text': '<p>This is not professional enough:</p>\n\n<pre><code>Stopwatch sw = Stopwatch.StartNew();\nPerformWork();\nsw.Stop();\n\nConsole.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds);\n</code></pre>\n\n<p>A more reliable version is:</p>\n\n<pre><code>PerformWork();\n\nint repeat = 1000;\n\nStopwatch sw = Stopwatch.StartNew();\nfor (int i = 0; i &lt; repeat; i++)\n{\n   PerformWork();\n}\n\nsw.Stop();\n\nConsole.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds / repeat);\n</code></pre>\n\n<p>In my real code, I will add GC.Collect call to change managed heap to a known state, and add Sleep call so that different intervals of code can be easily separated in ETW profile.</p>\n'}, {'answer_id': 64469019, 'author': 'Tono Nam', 'author_id': 637142, 'author_profile': 'https://Stackoverflow.com/users/637142', 'pm_score': 0, 'selected': False, 'text': '<p>Since I do not care to much about precision I ended up comparing them. I am capturing lots of packets on the network and I want to place the time when I receive each packet. Here is the code that tests 5 million iterations</p>\n<pre><code>    int iterations = 5000000;\n\n    // Test using datetime.now\n    {\n        var date = DateTime.UtcNow.AddHours(DateTime.UtcNow.Second);\n\n        var now = DateTime.UtcNow;\n\n        for (int i = 0; i &lt; iterations; i++)\n        {\n            if (date == DateTime.Now)\n                Console.WriteLine(&quot;it is!&quot;);\n        }\n        Console.WriteLine($&quot;Done executing {iterations} iterations using datetime.now. It took {(DateTime.UtcNow - now).TotalSeconds} seconds&quot;);\n    }\n\n    // Test using datetime.utcnow\n    {\n        var date = DateTime.UtcNow.AddHours(DateTime.UtcNow.Second);\n\n        var now = DateTime.UtcNow;\n\n        for (int i = 0; i &lt; iterations; i++)\n        {\n            if (date == DateTime.UtcNow)\n                Console.WriteLine(&quot;it is!&quot;);\n        }\n        Console.WriteLine($&quot;Done executing {iterations} iterations using datetime.utcnow. It took {(DateTime.UtcNow - now).TotalSeconds} seconds&quot;);\n    }\n\n    // Test using stopwatch\n    {\n        Stopwatch sw = new Stopwatch();\n        sw.Start();\n\n        var now = DateTime.UtcNow;\n\n        for (int i = 0; i &lt; iterations; i++)\n        {\n            if (sw.ElapsedTicks == DateTime.Now.Ticks)\n                Console.WriteLine(&quot;it is!&quot;);\n        }\n        Console.WriteLine($&quot;Done executing {iterations} iterations using stopwatch. It took {(DateTime.UtcNow - now).TotalSeconds} seconds&quot;);\n    }\n</code></pre>\n<p>The output is:</p>\n<pre><code>Done executing 5000000 iterations using datetime.now. It took 0.8685502 seconds \nDone executing 5000000 iterations using datetime.utcnow. It took 0.1074324 seconds \nDone executing 5000000 iterations using stopwatch. It took 0.9625021 seconds\n</code></pre>\n<p><strong>So in conclusion DateTime.UtcNow is the fastest if you do not care to much about precision</strong>. This also supports the answer <a href="https://stackoverflow.com/a/6986472/637142">https://stackoverflow.com/a/6986472/637142</a> from this question.</p>\n'}]
['https://Stackoverflow.com/questions/28637', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2469/']