-
Notifications
You must be signed in to change notification settings - Fork 56
Simple performance stopwatch
I often needed to know how long a process took. I could use BenchmarkDotNet
, but BenchmarkDotNet
its takes a long time to get the results and hard to setup so I built simpler performance method, called TimeThings
. TimeThings
is easy to use, (only needs three lines of code), you can add TimeThings
to your unit tests, and its pretty fast (~3 ms) so doesn't slow down your unit tests. I usually use TimeThings
to get a "quick and dirty" performance while I'm building a new application. However if the code performance is important I use BenchmarkDotNet
to get accurate timing, for instance I used BenchmarkDotNet
in performance is important Net.DistributedFileStoreCache.
I usually TimeThings
in my Xunit unit tests, and the code below shows a basic use, but you be aware most unit tests run in parallel, which affect the time a process takes. Therefore you need to run the Xunit's ON ITS OWN to get the correct performance timing. The code below shows a Xunit with the a TimeThings
- the result performance time is sent to your Test Explorer's output panel.
public class PerfBookJsonContext
{
private readonly ITestOutputHelper _output;
public PerfBookJsonContext(ITestOutputHelper output) => _output = output;
[Fact]
public void TestWithTimeThings()
{
//SETUP
//your test setup
//ATTEMPT
using (new TimeThings(output)) //The performance time it sent to your
{
//your process you need to test and
}
//VERIFY
//your test checks
}
}
The TimeThings
has a version which takes an Action<TimeThingResult>
which is fills in the performance data when the TimeThings
is disposed.
[Fact]
public void TestTimeThingResultReturn()
{
//SETUP
TimeThingResult result = null;
//ATTEMPT
using (new TimeThings(x => result = x))
{
Thread.Sleep(10);
}
//VERIFY
//your test checks
}
The TimeThings
examples shown so far only uses the first parameter, but there are two optional parameters. Here is the Xunit's TimeThings
class:
public TimeThings(ITestOutputHelper output, string message = "", int numRuns = 0)
And here are the types of output string you would get for the three possibilities.
new TimeThings | output string |
---|---|
new TimeThings(_output) | "took 1.64 ms." |
new TimeThings(_output, "Sample 1") | "Sample 1 took 1.64 ms." |
new TimeThings(_output, "read book", 500) | "500 x read book took 23.45 ms., ave. per run = 46.90 us." |
Note that the third version will return an average time by just dividing the overall time but the number of numRuns
, which is scaled to make the timing more useful. The time types are:
short name | full name |
---|---|
sec. | Seconds |
ms. | Milliseconds |
us. | Microseconds |
ns. | Nanoseconds |
END
- Testing against a PostgreSQL db
- Changes in EfCore.TestSupport 5
- Testing with production data
- Using an in-memory database (old)