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.
4 Answers
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.

- 110,061
- 20
- 134
- 146
-
You got it :) Glad I could help. – Donut Dec 09 '10 at 14:22
Use:
using System.Diagnostics;
...
var sw = Stopwatch.StartNew();
DoYaThing();
Console.WriteLine("{0} Elapsed", sw.Elapsed);

- 48,783
- 32
- 145
- 190
There's the high resolution timer ...
Also, iirc a TimeSpan can give you a measurement in ticks back.

- 4,813
- 2
- 29
- 55