We are beginning capture measurements of time to execute specific tasks throughout our code. Using the Stopwatch class is getting the job done, but the concern is that Stopwatch is effective for measuring time within a single function, or block of code, but not so much between different points in the application (multiple namespaces). Eventually will incorporate a an actual telemetry service, such as Application Insights, but for now we just want the times and will write them to a log.
My reference class to my Stopwatch getter/setter
namespace MyApp.Application.Contracts.Core.References
public class StopwatchReference
{
/// <summary>
/// The Timer is used to accurately measure the elapsed milliseconds of specific tasks
/// </summary>
public Stopwatch Timer { get; set; }
}
I start the watch in Method A
var startTime = new StopwatchReference();
startTime.Timer.Start();
The code we are timing runs through multiple methods in many different namespaces. It comes to completion in what we will call Method B. What is the proper way to stop this exact instance of the timer? Keep in mind, the system will have many users potentially making the same calls at the same time, so thread safety is our primary concern.
I am open to suggestions on alternative methods. Thanks in advance!
Assuming that tasks, you are talking about, are started in a well defined place in your code it is enough to measure time there e.g.:.
public void StartTask(Action task)
{
var sw = new Stopwatch();
task();
sw.Stop();
...
}
It doesn't matter which methods and namespaces are used by a given task.
UPDATE
If you want to measure time across mamy threads you may use a logging library like NLog to write to a log start/end of selected methods. NLog will also log thread id. Besides you have to log something like session id or user id to be able to correlate entries.
If you don't want to modify your code too much you can use the aspect oriented programming to inject logging to your application.
Finnally, you can analyse your logs manually, with regular exptressions or some data analysis tool. The first one that came to my mind is Kibana.
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