Any class in C# that can tell me clock tick, seconds consumed by a function
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.
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.
Use:
using System.Diagnostics;
...
var sw = Stopwatch.StartNew();
DoYaThing();
Console.WriteLine("{0} Elapsed", sw.Elapsed);
There's the high resolution timer ...
Also, iirc a TimeSpan can give you a measurement in ticks back.
You can check out the [System.TimeSpan]
class and wrap that around your method.
精彩评论