Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Become a C# Expert!

Join 137,214 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 2,273 people online right now. Registration is fast and FREE... Join Now!





Measure task execution time

This is a snippet used to measure the execution time of a task or process. It uses the System.Diagnostics.StopWatch to measure the time

Submitted By: PsychoCoder
Actions:
Rating:
Views: 488

Language: C#

Last Modified: January 2, 2008
Instructions: Pass the method the number of times to execute the task or process, results are returned in a HashTable format showing:

1) Total elapsed time
2) Milliseconds elapsed
3) Timer ticks elapsed

Snippet


  1. //Namespace reference
  2. using System;
  3. using System.Diagnostics;
  4.  
  5. /// <summary>
  6. /// method to measure the execution time of a
  7. /// task or process.
  8. /// </summary>
  9. /// <param name="num">Number of times to execute the task</param>
  10. /// <returns></returns>
  11. public Hashtable MeasureExecutionTime(int num)
  12. {
  13.     //HashTable instance to hold execution times
  14.     Hashtable time = new Hashtable();
  15.     Stopwatch timer = new Stopwatch();
  16.     try
  17.     {
  18.         //start your StopWatch
  19.         timer.Start();
  20.         for (int i = 1; i < num; i++)
  21.         {
  22.             //execute your process or task to be times
  23.         }
  24.         //stop the StopWatch once the processing is complete
  25.         timer.Stop();
  26.         //Add the values to our HashTable
  27.         time.Add("Elapsed: ", timer.Elapsed);
  28.         time.Add("In milliseconds: ", timer.ElapsedMilliseconds);
  29.         time.Add("In timer ticks: ", timer.ElapsedTicks);
  30.     }
  31.     catch (Exception ex)
  32.     {
  33.         time = null;
  34.         MessageBox.Show(ex.Message);
  35.     }
  36.     return time;
  37. }

Copy & Paste


Comments


sannoah 2008-08-05 04:55:29


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month