Overview
Currently, I have been working on speeding up my C# screensaver, and I thought
that it would be useful to know if my assumptions about where my code was
taking it's time were in fact correct. So I wrote this little tool.
Along the way I got to play with some new stuff, like the hash map, file access
and some control stuff I had not done yet. Hopefully I'll find something
to interest you as well.
Strategy
Basically, the way this code will work is to create a class which encapsulates a
hash table between a string and an instance of a class that holds data about
our function. The hash table and the functions provided will be static -
we don't want more than one instance of our code running. The class will
have a start and stop method, which apart from making sure there is no
crossover, or invalid calls, will essentially just maintain timers in the class
objects to keep track of the time spent in each function we trace. A
global timer will tell us how long the code ran for to find out what percentage
of running time was in functions we were tracing.
Code reuse in C#
In order to build the main object, I created a new project, and chose the class
library option. This builds a dll file which can be added to another
project by choosing Project | Add Reference from the menu. Then it's a
case of browsing to the dll file, and it will be copied into your local
directory. Note so long as you are using it, you need to distribute this
dll with your program. In this case, it's more of a debugging tool, so
I'd expect you'd remove it when testing was done.
A small problem.
I found while writing this tool that if I call DateTime.Now()
, run a small
function and then call it again, DateTime2 - DateTime1
gives a negative
value. I had to check for this, and log a time of 1 millisecond
instead.
Output to disk
The report class has a method which uses a StreamWriter
to write the report out
as a text file. If you're not familiar with writing text files in C#, you
might find it useful to examine.
Using the Code
A second project is provided which shows how to use the tool. First you
need to add the supplied dll, and then simply call
CodeTimer.CodeTime.Start(FunctionName);
and
CodeTimer.CodeTime.Stop(FunctionName);
on either end of the function you want
to time, and be careful not to time a function which calls another function
being timed. Currently the calls do not nest, and the tool detects
this and crashes. The CodeTimer.CodeTime.Report();
call can be triggered
by the program, or set up to come up when the class is destroyed, giving a
report at the end of a run.
Summary
This article has been low on detail simply because I expect people to get more
out of the tool than the code, which is not that involved. Having
explained how it is set up, hopefully if there's something that interests you,
it will be clear in the code. Otherwise, I hope the tool itself is of use
to you.