I would like to understand if I can use the #if in my development scenario. I would like to capture the execution time each method in the production environment.
For that I am thinking to use the stopwatch class and write the elapsed time in a log based on the condition set in the config file. In the config file we have an option called Loglevel which holds values such as "Error,debug,info,All". In production, we set the loglevel type as "Error" to capture only errors. So the logs that I am going to write will not be written in the files. When there is an issue reported by customer, we will change the error log setting to debug so all the info will be written in the logs.
However, I don't want to take the approach as unnecessary codes of lines are being executed even though I set the LogLevel value as to capture only Error. So planning to use the #if debug to capture the execution times. I am not sure if this works in production environment without replacing dll or project files which are built in release mode. Will #if debug work in release mode? If so how do I make the lines of code executed to capture execution time without replacing files and just with configuration change? TIA.
Below is the sample code
public int process()
{
#if Debug
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
#endif
Int a = 20;
Int b = 30;
Int c = a+ b;
#if Debug
stopwatch.Stop();
this.WritePerformanceLog(0, System.Reflection.MethodInfo.GetCurrentMethod().ReflectedType.ToString()+" "+System.Reflection.MethodInfo.GetCurrentMethod().Name, "API", DateTime.UtcNow, DateTime.UtcNow,stopwatch.Elapsed.ToString());
stopwatch = null;
#endif
return C
}
Use a profiler.
While stopwatch has a fairly low overhead. Writing to the log for each method call will just destroy your performance. Sprinkling your code with #if-directives to enable stopwatches will turn your code into an unreadable mess, and likely not even do a good job of measuring performance anyway.
Profilers are designed for exactly this purpose, should work without changing the assemblies at all, and should have fairly low overhead, depending on the mode you are using. Visual studio has a profiler built in, but there are also third party ones.
A stopwatch may be useful to check the runtime of specific methods that are known to be slow, and where you might want log anyway, so adding a stopwatch is essentially free, an may be useful diagnostic tool in case something like a database call or similar take much longer than expected.