I'm trying to find the best way to measure the duration of a method to log them on Application Insights, I know it's possible if we do something like this:
public void TestMethod()
{
var sw = Stopwatch.StartNew();
//code here
sw.Stop();
Console.WriteLine("Time elapsed: {0}", sw.Elapsed);
}
But, as you suppose, I don't want to write it on all the methods, ideally, I want to use a decorator, something similar to this.
[MeasureTime]
public void TestMethod()
{
//code here
}
Or something similar. So my question is: How can I build something like this? Is there a better way to do it?
Thanks in advance!
The CPU time is represented by the data type clock_t, which is the number of ticks of the clock signal. By dividing the number of clock cycles by the clocks per seconds, you have the total amount of time a process has been actively using a CPU after an arbitrary event.
1) Create a loop around whatneeds to be measured, that executes 10, 100, or 1000 times or more. Measure execution time to the nearest 10 msec. Then divide that time bythe number of times the loop executed. If the loop executed 1000 timesusing a 10 msec clock, you obtain a resolution of 10 µsec for theloop.
If the system is specified asfrequency or rate (e.g. “execute task at 40 Hz”) then T i =1/frequency (40 Hz means T i =25 msec).
The currentTimeMillis() method returns the current time in milliseconds. To find the elapsed time for a method you can get the difference between time values before and after the execution of the desired method. The nanoTime() method returns the current time in nano seconds.
One way to do this would be to use an assembly weaver like 'Fody' with an extension that does exactly what you are looking for. Please see this link for an example extension: https://github.com/Fody/MethodTimer
How Fody works is it injects code into your code-base at compile time, utilising attributes as you have suggested in your question. The provided extension does just as you have described using a stopwatch to log the execution time of your code.
An example of usage:
Once the library is installed, you can add the annotation [Time] to the methods you wish to measure:
[Time]
public void TestMethod()
{
//code here
}
You can then create a custom interceptor (A static class that will be automatically picked up by the Fody extension) which you can use to add a metric track into application insights:
public static class MethodTimeLogger
{
public static void Log(MethodBase methodBase, long milliseconds)
{
var sample = new MetricTelemetry();
sample.Name = methodBase.Name;
sample.Value = milliseconds;
// Your telemetryClient here
telemetryClient.TrackMetric(sample);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With