• Stars
    star
    10,347
  • Rank 3,338 (Top 0.07 %)
  • Language
    C#
  • License
    MIT License
  • Created over 11 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Powerful .NET library for benchmarking

NuGet MyGet Downloads Stars License Twitter

BenchmarkDotNet helps you to transform methods into benchmarks, track their performance, and share reproducible measurement experiments. It's no harder than writing unit tests! Under the hood, it performs a lot of magic that guarantees reliable and precise results thanks to the perfolizer statistical engine. BenchmarkDotNet protects you from popular benchmarking mistakes and warns you if something is wrong with your benchmark design or obtained measurements. The results are presented in a user-friendly form that highlights all the important facts about your experiment. BenchmarkDotNet is already adopted by 19100+ GitHub projects including .NET Runtime, .NET Compiler, .NET Performance, and many others.

It's easy to start writing benchmarks, check out the following example (copy-pastable version is here):

[SimpleJob(RuntimeMoniker.Net472, baseline: true)]
[SimpleJob(RuntimeMoniker.NetCoreApp30)]
[SimpleJob(RuntimeMoniker.NativeAot70)]
[SimpleJob(RuntimeMoniker.Mono)]
[RPlotExporter]
public class Md5VsSha256
{
    private SHA256 sha256 = SHA256.Create();
    private MD5 md5 = MD5.Create();
    private byte[] data;

    [Params(1000, 10000)]
    public int N;

    [GlobalSetup]
    public void Setup()
    {
        data = new byte[N];
        new Random(42).NextBytes(data);
    }

    [Benchmark]
    public byte[] Sha256() => sha256.ComputeHash(data);

    [Benchmark]
    public byte[] Md5() => md5.ComputeHash(data);
}

BenchmarkDotNet automatically runs the benchmarks on all the runtimes, aggregates the measurements, and prints a summary table with the most important information:

BenchmarkDotNet=v0.12.0, OS=Windows 10.0.17763.805 (1809/October2018Update/Redstone5)
Intel Core i7-7700K CPU 4.20GHz (Kaby Lake), 1 CPU, 8 logical and 4 physical cores
  [Host]       : .NET Framework 4.7.2 (4.7.3468.0), X64 RyuJIT
  Net472       : .NET Framework 4.7.2 (4.7.3468.0), X64 RyuJIT
  NetCoreApp30 : .NET Core 3.0.0 (CoreCLR 4.700.19.46205, CoreFX 4.700.19.46214), X64 RyuJIT
  NativeAot70  : .NET 7.0.0-preview.4.22172.7, X64 NativeAOT
  Mono         : Mono 6.4.0 (Visual Studio), X64


| Method |       Runtime |     N |       Mean |     Error |    StdDev | Ratio |
|------- |-------------- |------ |-----------:|----------:|----------:|------:|
| Sha256 |    .NET 4.7.2 |  1000 |   7.735 us | 0.1913 us | 0.4034 us |  1.00 |
| Sha256 | .NET Core 3.0 |  1000 |   3.989 us | 0.0796 us | 0.0745 us |  0.50 |
| Sha256 | NativeAOT 7.0 |  1000 |   4.091 us | 0.0811 us | 0.1562 us |  0.53 |
| Sha256 |          Mono |  1000 |  13.117 us | 0.2485 us | 0.5019 us |  1.70 |
|        |               |       |            |           |           |       |
|    Md5 |    .NET 4.7.2 |  1000 |   2.872 us | 0.0552 us | 0.0737 us |  1.00 |
|    Md5 | .NET Core 3.0 |  1000 |   1.848 us | 0.0348 us | 0.0326 us |  0.64 |
|    Md5 | NativeAOT 7.0 |  1000 |   1.817 us | 0.0359 us | 0.0427 us |  0.63 |
|    Md5 |          Mono |  1000 |   3.574 us | 0.0678 us | 0.0753 us |  1.24 |
|        |               |       |            |           |           |       |
| Sha256 |    .NET 4.7.2 | 10000 |  74.509 us | 1.5787 us | 4.6052 us |  1.00 |
| Sha256 | .NET Core 3.0 | 10000 |  36.049 us | 0.7151 us | 1.0025 us |  0.49 |
| Sha256 | NativeAOT 7.0 | 10000 |  36.253 us | 0.7076 us | 0.7571 us |  0.49 |
| Sha256 |          Mono | 10000 | 116.350 us | 2.2555 us | 3.0110 us |  1.58 |
|        |               |       |            |           |           |       |
|    Md5 |    .NET 4.7.2 | 10000 |  17.308 us | 0.3361 us | 0.4250 us |  1.00 |
|    Md5 | .NET Core 3.0 | 10000 |  15.726 us | 0.2064 us | 0.1930 us |  0.90 |
|    Md5 | NativeAOT 7.0 | 10000 |  15.627 us | 0.2631 us | 0.2461 us |  0.89 |
|    Md5 |          Mono | 10000 |  30.205 us | 0.5868 us | 0.6522 us |  1.74 |

The measured data can be exported to different formats (md, html, csv, xml, json, etc.) including plots:

Supported runtimes: .NET 5+, .NET Framework 4.6.1+, .NET Core 2.0+, Mono, NativeAOT
Supported languages: C#, F#, Visual Basic
Supported OS: Windows, Linux, macOS
Supported architectures: x86, x64, ARM, ARM64, Wasm and LoongArch64

Features

BenchmarkDotNet has tons of features that are essential in comprehensive performance investigations. Four aspects define the design of these features: simplicity, automation, reliability, and friendliness.

Simplicity

You shouldn't be an experienced performance engineer if you want to write benchmarks. You can design very complicated performance experiments in the declarative style using simple APIs.

For example, if you want to parameterize your benchmark, mark a field or a property with [Params(1, 2, 3)]: BenchmarkDotNet will enumerate all of the specified values and run benchmarks for each case. If you want to compare benchmarks with each other, mark one of the benchmarks as the baseline via [Benchmark(Baseline = true)]: BenchmarkDotNet will compare it with all of the other benchmarks. If you want to compare performance in different environments, use jobs. For example, you can run all the benchmarks on .NET Core 3.0 and Mono via [SimpleJob(RuntimeMoniker.NetCoreApp30)] and [SimpleJob(RuntimeMoniker.Mono)].

If you don't like attributes, you can call most of the APIs via the fluent style and write code like this:

ManualConfig.CreateEmpty() // A configuration for our benchmarks
    .AddJob(Job.Default // Adding first job
        .WithRuntime(ClrRuntime.Net472) // .NET Framework 4.7.2
        .WithPlatform(Platform.X64) // Run as x64 application
        .WithJit(Jit.LegacyJit) // Use LegacyJIT instead of the default RyuJIT
        .WithGcServer(true) // Use Server GC
    ).AddJob(Job.Default // Adding second job
        .AsBaseline() // It will be marked as baseline
        .WithEnvironmentVariable("Key", "Value") // Setting an environment variable
        .WithWarmupCount(0) // Disable warm-up stage
    );

If you prefer command-line experience, you can configure your benchmarks via the console arguments in any console application (other types of applications are not supported).

Automation

Reliable benchmarks always include a lot of boilerplate code.

Let's think about what you should do in a typical case. First, you should perform a pilot experiment and determine the best number of method invocations. Next, you should execute several warm-up iterations and ensure that your benchmark achieved a steady state. After that, you should execute the main iterations and calculate some basic statistics. If you calculate some values in your benchmark, you should use it somehow to prevent dead code elimination. If you use loops, you should care about the effect of the loop unrolling on your results (which may depend on the processor architecture). Once you get results, you should check for some special properties of the obtained performance distribution like multimodality or extremely high outliers. You should also evaluate the overhead of your infrastructure and deduct it from your results. If you want to test several environments, you should perform the measurements in each of them and manually aggregate the results.

If you write this code from scratch, it's easy to make a mistake and spoil your measurements. Note that it's a shortened version of the full checklist that you should follow during benchmarking: there are a lot of additional hidden pitfalls that should be handled appropriately. Fortunately, you shouldn't worry about it because BenchmarkDotNet will perform this boring and time-consuming stuff for you.

Moreover, the library can help you with some advanced tasks that you may want to perform during the investigation. For example, BenchmarkDotNet can measure the managed and native memory traffic and print disassembly listings for your benchmarks.

Reliability

A lot of hand-written benchmarks produce wrong numbers that lead to incorrect business decisions. BenchmarkDotNet protects you from most of the benchmarking pitfalls and allows achieving high measurement precision.

You shouldn't worry about the perfect number of method invocation, the number of warm-up and actual iterations: BenchmarkDotNet tries to choose the best benchmarking parameters and achieve a good trade-off between the measurement prevision and the total duration of all benchmark runs. So, you shouldn't use any magic numbers (like "We should perform 100 iterations here"), the library will do it for you based on the values of statistical metrics.

BenchmarkDotNet also prevents benchmarking of non-optimized assemblies that were built using DEBUG mode because the corresponding results will be unreliable. The library will print a warning if you have an attached debugger, if you use a hypervisor (HyperV, VMware, VirtualBox), or if you have any other problems with the current environment.

During 6+ years of development, we faced dozens of different problems that may spoil your measurements. Inside BenchmarkDotNet, there are a lot of heuristics, checks, hacks, and tricks that help you to increase the reliability of the results.

Friendliness

Analysis of performance data is a time-consuming activity that requires attentiveness, knowledge, and experience. BenchmarkDotNet performs the main part of this analysis for you and presents results in a user-friendly form.

After the experiments, you get a summary table that contains a lot of useful data about the executed benchmarks. By default, it includes only the most important columns, but they can be easily customized. The column set is adaptive and depends on the benchmark definition and measured values. For example, if you mark one of the benchmarks as a baseline, you will get additional columns that will help you to compare all the benchmarks with the baseline. By default, it always shows the Mean column, but if we detected a vast difference between the Mean and the Median values, both columns will be presented.

BenchmarkDotNet tries to find some unusual properties of your performance distributions and prints nice messages about it. For example, it will warn you in case of multimodal distribution or high outliers. In this case, you can scroll the results up and check out ASCII-style histograms for each distribution or generate beautiful png plots using [RPlotExporter].

BenchmarkDotNet doesn't overload you with data; it shows only the essential information depending on your results: it allows you to keep the summary small for primitive cases and extend it only for complicated cases. Of course, you can request any additional statistics and visualizations manually. If you don't customize the summary view, the default presentation will be as much user-friendly as possible. :)

Learn more about benchmarking

BenchmarkDotNet is not a silver bullet that magically makes all of your benchmarks correct and analyzes the measurements for you. Even if you use this library, you still should know how to design benchmark experiments and how to make correct conclusions based on the raw data. If you want to know more about benchmarking methodology and good practices, it's recommended to read a book by Andrey Akinshin (the BenchmarkDotNet project lead): "Pro .NET Benchmarking". Use this in-depth guide to correctly design benchmarks, measure key performance metrics of .NET applications, and analyze results. This book presents dozens of case studies to help you understand complicated benchmarking topics. You will avoid common pitfalls, control the accuracy of your measurements, and improve the performance of your software.

Contributions are welcome!

BenchmarkDotNet is already a stable full-featured library that allows performing performance investigation on a professional level. And it continues to evolve! We add new features all the time, but we have too many new cool ideas. Any help will be appreciated. You can develop new features, fix bugs, improve the documentation, or do some other cool stuff.

If you want to contribute, check out the Contributing guide and up-for-grabs issues. If you have new ideas or want to complain about bugs, feel free to create a new issue. Let's build the best tool for benchmarking together!

Code of Conduct

This project has adopted the code of conduct defined by the Contributor Covenant to clarify expected behavior in our community. For more information, see the .NET Foundation Code of Conduct.

Sponsors

BenchmarkDotNet is supported by the AWS Open Source Software Fund.

More Repositories

1

aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
C#
33,217
star
2

maui

.NET MAUI is the .NET Multi-platform App UI, a framework for building native device applications spanning mobile, tablet, and desktop.
C#
21,888
star
3

core

.NET news, announcements, release notes, and more!
PowerShell
20,805
star
4

roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
C#
18,994
star
5

corefx

This repo is used for servicing PR's for .NET Core 2.1 and 3.1. Please visit us at https://github.com/dotnet/runtime
17,793
star
6

runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
C#
15,172
star
7

coreclr

CoreCLR is the runtime for .NET Core. It includes the garbage collector, JIT compiler, primitive data types and low-level classes.
12,807
star
8

efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
C#
12,774
star
9

AspNetCore.Docs

Documentation for ASP.NET Core
C#
12,619
star
10

csharplang

The official repo for the design of the C# programming language
C#
11,300
star
11

orleans

Cloud Native application framework for .NET
C#
9,460
star
12

blazor

Blazor moved to https://github.com/dotnet/aspnetcore
PowerShell
9,348
star
13

machinelearning

ML.NET is an open source and cross-platform machine learning framework for .NET.
C#
8,456
star
14

reactive

The Reactive Extensions for .NET
C#
6,687
star
15

wpf

WPF is a .NET Core UI framework for building Windows desktop applications.
C#
6,346
star
16

tye

Tye is a tool that makes developing, testing, and deploying microservices and distributed applications easier. Project Tye includes a local orchestrator to make developing microservices easier and the ability to deploy microservices to Kubernetes with minimal configuration.
C#
5,290
star
17

msbuild

The Microsoft Build Engine (MSBuild) is the build platform for .NET and Visual Studio.
C#
5,215
star
18

MQTTnet

MQTTnet is a high performance .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker). The implementation is based on the documentation from http://mqtt.org/.
C#
4,466
star
19

winforms

Windows Forms is a .NET UI framework for building Windows desktop applications.
C#
4,402
star
20

docs

This repository contains .NET Documentation.
4,246
star
21

Silk.NET

The high-speed OpenGL, OpenCL, OpenAL, OpenXR, GLFW, SDL, Vulkan, Assimp, WebGPU, and DirectX bindings library your mother warned you about.
C#
4,118
star
22

machinelearning-samples

Samples for ML.NET, an open source and cross-platform machine learning framework for .NET.
PowerShell
4,061
star
23

dotnet-docker

Docker images for .NET and the .NET Tools.
Dockerfile
4,033
star
24

Open-XML-SDK

Open XML SDK by Microsoft
C#
4,014
star
25

fsharp

The F# compiler, F# core library, F# language service, and F# tooling integration for Visual Studio
F#
3,892
star
26

docfx

Static site generator for .NET API documentation.
C#
3,663
star
27

cli

The .NET Core command-line (CLI) tools, used for building .NET Core apps and libraries through your development flow (compiling, NuGet package management, running, testing, ...).
3,488
star
28

command-line-api

Command line parsing, invocation, and rendering of terminal output.
C#
3,095
star
29

roslynator

Roslynator is a set of code analysis tools for C#, powered by Roslyn.
C#
3,067
star
30

standard

This repo is building the .NET Standard
3,067
star
31

aspnet-api-versioning

Provides a set of libraries which add service API versioning to ASP.NET Web API, OData with ASP.NET Web API, and ASP.NET Core.
C#
3,027
star
32

corert

This repo contains CoreRT, an experimental .NET Core runtime optimized for AOT (ahead of time compilation) scenarios, with the accompanying compiler toolchain.
C#
2,908
star
33

samples

Sample code referenced by the .NET documentation
C#
2,896
star
34

try

Try .NET provides developers and content authors with tools to create interactive experiences.
TypeScript
2,884
star
35

interactive

.NET Interactive combines the power of .NET with many other languages to create notebooks, REPLs, and embedded coding experiences. Share code, explore data, write, and learn across your apps in ways you couldn't before.
C#
2,879
star
36

vscode-csharp

Official C# support for Visual Studio Code
TypeScript
2,852
star
37

sdk

Core functionality needed to create .NET Core projects, that is shared between Visual Studio and CLI
C#
2,516
star
38

extensions

This repository contains a suite of libraries that provide facilities commonly needed when creating production-ready applications.
C#
2,361
star
39

Docker.DotNet

🐳 .NET (C#) Client Library for Docker API
C#
2,242
star
40

maui-samples

Samples for .NET Multi-Platform App UI (.NET MAUI)
C#
2,219
star
41

pinvoke

A library containing all P/Invoke code so you don't have to import it every time. Maintained and updated to support the latest Windows OS.
C#
2,115
star
42

spark

.NET for Apache® Spark™ makes Apache Spark™ easily accessible to .NET developers.
C#
2,018
star
43

iot

This repo includes .NET Core implementations for various IoT boards, chips, displays and PCBs.
C#
1,932
star
44

android

.NET for Android provides open-source bindings of the Android SDK for use with .NET managed languages such as C#
C#
1,897
star
45

format

Home for the dotnet-format command
C#
1,736
star
46

wcf

This repo contains the client-oriented WCF libraries that enable applications built on .NET Core to communicate with WCF services.
C#
1,693
star
47

Comet

Comet is an MVU UIToolkit written in C#
C#
1,654
star
48

dotNext

Next generation API for .NET
C#
1,597
star
49

templating

This repo contains the Template Engine which is used by dotnet new
C#
1,594
star
50

roslyn-analyzers

C#
1,577
star
51

llilc

This repo contains LLILC, an LLVM based compiler for .NET Core. It includes a set of cross-platform .NET code generation tools that enables compilation of MSIL byte code to LLVM supported platforms.
C++
1,512
star
52

infer

Infer.NET is a framework for running Bayesian inference in graphical models
C#
1,500
star
53

EntityFramework.Docs

Documentation for Entity Framework Core and Entity Framework 6
PowerShell
1,477
star
54

corefxlab

This repo is for experimentation and exploring new ideas that may or may not make it into the main corefx repo.
C#
1,463
star
55

ef6

This is the codebase for Entity Framework 6 (previously maintained at https://entityframework.codeplex.com). Entity Framework Core is maintained at https://github.com/dotnet/efcore.
C#
1,400
star
56

ResXResourceManager

Manage localization of all ResX-Based resources in one central place.
C#
1,311
star
57

announcements

Subscribe to this repo to be notified of Announcements and changes in .NET Core.
1,263
star
58

installer

.NET SDK Installer
C#
1,261
star
59

codeformatter

Tool that uses Roslyn to automatically rewrite the source to follow our coding styles
C#
1,235
star
60

Nerdbank.GitVersioning

Stamp your assemblies, packages and more with a unique version generated from a single, simple version.json file and include git commit IDs for non-official builds.
C#
1,223
star
61

MobileBlazorBindings

Experimental Mobile Blazor Bindings - Build native and hybrid mobile apps with Blazor
C#
1,203
star
62

runtimelab

This repo is for experimentation and exploring new ideas that may or may not make it into the main dotnet/runtime repo.
1,181
star
63

ILMerge

ILMerge is a static linker for .NET Assemblies.
C#
1,175
star
64

try-convert

Helping .NET developers port their projects to .NET Core!
C#
1,146
star
65

sourcelink

Source Link enables a great source debugging experience for your users, by adding source control metadata to your built assets
C#
1,136
star
66

diagnostics

This repository contains the source code for various .NET Core runtime diagnostic tools and documents.
C++
1,092
star
67

upgrade-assistant

A tool to assist developers in upgrading .NET Framework applications to .NET 6 and beyond
C#
982
star
68

project-system

The .NET Project System for Visual Studio
C#
967
star
69

try-samples

C#
920
star
70

ClangSharp

Clang bindings for .NET written in C#
C#
905
star
71

TorchSharp

A .NET library that provides access to the library that powers PyTorch.
C#
891
star
72

designs

This repo is used for reviewing new .NET designs.
C#
843
star
73

LLVMSharp

LLVM bindings for .NET Standard written in C# using ClangSharp
C#
837
star
74

crank

Benchmarking infrastructure for applications
C#
819
star
75

DataGridExtensions

Modular extensions for the WPF DataGrid control
C#
805
star
76

SqlClient

Microsoft.Data.SqlClient provides database connectivity to SQL Server for .NET applications.
C#
728
star
77

intro-to-dotnet-web-dev

Get Started as a Web Developer with .NET, C#, and ASP.NET Core
C#
690
star
78

arcade

Tools that provide common build infrastructure for multiple .NET Foundation projects.
C#
664
star
79

Microsoft.Maui.Graphics

An experimental cross-platform native graphics library.
C#
657
star
80

HttpRepl

The HTTP Read-Eval-Print Loop (REPL) is a lightweight, cross-platform command-line tool that's supported everywhere .NET Core is supported and is used for making HTTP requests to test ASP.NET Core web APIs and view their results.
C#
651
star
81

csharp-notebooks

Get started learning C# with C# notebooks powered by .NET Interactive and VS Code.
Jupyter Notebook
629
star
82

performance

This repo contains benchmarks used for testing the performance of all .NET Runtimes
F#
620
star
83

cli-lab

A guided tool will be provided to enable the controlled clean up of a system such that only the desired versions of the Runtime and SDKs remain.
C#
609
star
84

Microsoft.Maui.Graphics.Controls

Experimental Microsoft.Maui.Graphics.Controls - Build drawn controls (Cupertino, Fluent and Material)
C#
608
star
85

Scaffolding

Code generators to speed up development.
C#
596
star
86

csharpstandard

Working space for ECMA-TC49-TG2, the C# standard committee.
C#
596
star
87

WatsonTcp

WatsonTcp is the easiest way to build TCP-based clients and servers in C#.
C#
585
star
88

dotnet-console-games

Game examples implemented as .NET console applications primarily for providing education and inspiration. :)
C#
569
star
89

dotnet-api-docs

.NET API reference documentation (.NET 5+, .NET Core, .NET Framework)
C#
558
star
90

dotnet-docker-samples

The .NET Core Docker samples have moved to https://github.com/dotnet/dotnet-docker/tree/master/samples
C#
543
star
91

dotnet-monitor

This repository contains the source code for .NET Monitor - a tool that allows you to gather diagnostic data from running applications using HTTP endpoints
C#
527
star
92

Nerdbank.Streams

Specialized .NET Streams and pipes for full duplex in-proc communication, web sockets, and multiplexing
C#
514
star
93

Kerberos.NET

A Kerberos implementation built entirely in managed code.
C#
513
star
94

blazor-samples

HTML
483
star
95

buildtools

Build tools that are necessary for building the .NET Core projects
479
star
96

roslyn-sdk

Roslyn-SDK templates and Syntax Visualizer
C#
470
star
97

core-setup

Installer packages for the .NET Core runtime and libraries
455
star
98

training-tutorials

Getting started tutorials for C# and ASP.NET
C#
414
star
99

WatsonWebserver

Watson is the fastest, easiest way to build scalable RESTful web servers and services in C#.
C#
407
star
100

razor

Compiler and tooling experience for Razor ASP.NET Core apps in Visual Studio, Visual Studio for Mac, and VS Code.
C#
390
star