-
Notifications
You must be signed in to change notification settings - Fork 1
Home
CodeTimer provides an easy way to add timing to procedure-style methods. It helps to provides visibility into the cost of individual code segments within a method.
CodeTimer helps to simplify the concerns for adding timing code to your software. Those concerns typically involve:
- Set up a Timer
- Adding variables to store timer values
- Formatting a string to display timing output
- Writing the formatting string to an output source - e.g. ILogger, Console, etc.
The following code shows an example of what these steps would typically look like without using CodeTimer.
var sw = Stopwatch.StartNew();
var timings = "";
// Do some work
var t1 = sw.ElapsedMilliseconds;
// Do some more work
var t2 = sw.ElapsedMilliseconds;
long t3;
long t4;
if (isCreating)
{
// Do something
t3 = sw.ElapsedMilliseconds;
// And again
t4 = sw.ElapsedMilliseconds;
}
else
{
// Do something
t3 = sw.ElapsedMilliseconds;
// And again
t4 = sw.ElapsedMilliseconds;
}
timings = $"{t1}-{t2}-{t3}-{t4}";
var ceiling = 1500; // 1500ms
if (sw.ElapsedMilliseconds >= ceiling)
{
localLogger.LogError($"MyMethod timings - {timings}");
}
By using CodeTimer, we can remove all of the extraneous concerns mentioned above and, instead, focus on our actual application code without timing code getting too much in the way. The next snippet shows the previous sample rewritten using CodeTimer:
var codeTimer = new CodeTimer.CodeTimer("MyMethod") {
ExpectedMilliseconds = 1500
};
// Do some work
codeTimer.Mark("Did work");
// Do some more work
codeTimer.Mark("Did morework");
if (isCreating)
{
// Do something
codeTimer.Mark("Did something");
// And again
codeTimer.Mark("Did something again");
}
else
{
// Do something
codeTimer.Mark("Did something");
// And again
codeTimer.Mark("Did something again");
}
codeTimer.Complete();
It is a useful diagnostic tool for when you need some extra information about how your code is performing. Ideally, you would use something like Application Insights to capture run-time diagnostics and then delve into your application logs to look at code-timer information when you want to verify segment costs for costly methods and requests.
CodeTimer is not a logger, but it works with the .NET Core ILogger to write Information and Warning (or Error) messages to the log for timed pieces of code. While code-timer can write verbose and non-verbose format messages to a log, you will still need to configure an ILogger in your application alongside other good logging tools such a Serilog so that you can tweak logging settings in different environments.
For further information refer to the Logging page