3

Is there a class in C# that can give me clock ticks, seconds consumed by a method? I guess I have two wrap that functionality around function to time the ticks and seconds taken up.

Infinite Recursion
  • 6,511
  • 28
  • 39
  • 51

4 Answers4

11

You could use the System.Diagnostics.Stopwatch class.

Stopwatch sw = new Stopwatch();
sw.Start();

// Your method call here...

sw.Stop();

// Get the elapsed time
TimeSpan elapsed = sw.Elapsed;

From here, you can use the TimeSpan.Ticks or the TimeSpan.TotalSeconds properties to determine the elapsed ticks or elapsed seconds, respectively.

If you wanted to, you could use a method along the following lines to "wrap" that functionality around a function, as you mentioned (just an idea, you'd probably want to tweak this code to suit your specific purposes -- passing in arguments, etc.):

public static T ExecuteWithElapsedTime<T>(Func<T> function, out TimeSpan elapsedTime)
{
   T rval;

   Stopwatch sw = new Stopwatch();
   sw.Start();
   rval = function();
   sw.Stop();
   elapsedTime = sw.Elapsed;

   return rval;
}

And you could call it like this (where myFunc is a function that returns an int):

TimeSpan elapsed;
int result = ExecuteWithElapsedTime(myFunc, out elapsed);

Might be simpler though to not even bother with a method like this, and just put the Stopwatch code inline with your method call.

Donut
  • 110,061
  • 20
  • 134
  • 146
3

Use:

using System.Diagnostics;

...

var sw = Stopwatch.StartNew();
DoYaThing();
Console.WriteLine("{0} Elapsed", sw.Elapsed);
John Gietzen
  • 48,783
  • 32
  • 145
  • 190
0

There's the high resolution timer ...

Also, iirc a TimeSpan can give you a measurement in ticks back.

Tim Barrass
  • 4,813
  • 2
  • 29
  • 55
0

You can check out the [System.TimeSpan] class and wrap that around your method.

Hps
  • 1,177
  • 8
  • 9