Post

Using BenchmarkDotNet with Azure Functions

Using BenchmarkDotNet with Azure Functions

BenchmarkDotNet is a tool for benchmarking .NET applications. Azure Functions is a serverless web application offering. You can put these together to benchmark your Azure Functions applications.

Setup

Ultimately, it looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using BenchmarkDotNet.Attributes;
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;

namespace FunctionAppBenchmark
{
    [InProcess]
    public class Benchmarks
    {
        private const int FunctionsPort = 7071;

        private Process funcProcess;
        private HttpClient httpClient;

        [GlobalSetup]
        public void GlobalSetup()
        {
            funcProcess = new Process
            {
                StartInfo =
                {
                    FileName = "func.exe",
                    Arguments = $"start -p {FunctionsPort}",
                    WorkingDirectory = "src/FunctionApp"
                }
            };

            var started = funcProcess.Start();

            if (!started)
            {
                throw new Exception("func.exe was not started.");
            }

            httpClient = new HttpClient
            {
                BaseAddress = new Uri($"http://localhost:{FunctionsPort}")
            };
        }

        [GlobalCleanup]
        public void GlobalCleanup()
        {
            if (!funcProcess.HasExited)
            {
                funcProcess.Kill();
            }
        }

        [Benchmark]
        public async Task FastEndpoint()
        {
            var response = await httpClient.GetAsync("/api/run");

            response.EnsureSuccessStatusCode();
        }

        [Benchmark]
        public async Task SlowEndpoint()
        {
            var response = await httpClient.GetAsync("/api/run-slow");

            response.EnsureSuccessStatusCode();
        }
    }
}

Run the benchmark

Build and run the Release build:

1
2
dotnet build -c Release
dotnet .\tests\FunctionAppBenchmark\bin\Release\netcoreapp3.1\FunctionAppBenchmark.dll

which produces the following:

1
2
3
4
5
6
BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19042
Intel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.1.403
  [Host] : .NET Core 3.1.9 (CoreCLR 4.700.20.47201, CoreFX 4.700.20.47203), X64 RyuJIT

Job=InProcess  Toolchain=InProcessEmitToolchain
MethodMeanErrorStdDev
FastEndpoint2.988 ms0.1073 ms0.3044 ms
SlowEndpoint2,030.517 ms10.8453 ms10.1447 ms

A complete sample is available at https://github.com/kendaleiv/AzureFunctionsCSharpBenchmarkDotNet. Happy benchmarking!

This post is licensed under CC BY 4.0 by the author.