DateTime.Now v DateTime.UtcNow benchmark




Date Added (UTC):

15 Apr 2024 @ 00:52

Date Updated (UTC):

15 Apr 2024 @ 00:55


.NET Version(s):

.NET 8

Tag(s):


Added By:
Profile Image

Blog   
Ireland    
.NET Developer and tech lead from Ireland!

Benchmark Results:





Benchmark Code:



using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Columns;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Reports;
using System;

[Config(typeof(Config))]
[HideColumns(Column.Job, Column.RatioSD, Column.AllocRatio)]
[MemoryDiagnoser]
public class DateTimeBenchmark
{
    [Benchmark(Baseline = true)]
    public DateTime DateTimeNow() => DateTime.Now;

    [Benchmark]
    public DateTime DateTimeUtcNow() => DateTime.UtcNow;

    private class Config : ManualConfig
    {
        public Config()
        {
            AddJob(Job.Default.WithId(".NET 8").WithRuntime(CoreRuntime.Core80));

            SummaryStyle =
                SummaryStyle.Default.WithRatioStyle(RatioStyle.Trend);
        }
    }
}

// .NET 8
public DateTime DateTimeNow()
{
    return DateTime.Now;
}
// .NET 8
public DateTime DateTimeUtcNow()
{
    return DateTime.UtcNow;
}

// .NET 8
.method public hidebysig 
    instance valuetype [System.Runtime]System.DateTime DateTimeNow () cil managed 
{
    .custom instance void [BenchmarkDotNet.Annotations]BenchmarkDotNet.Attributes.BenchmarkAttribute::.ctor(int32, string) = (
        01 00 17 00 00 00 01 5f 01 00 54 02 08 42 61 73
        65 6c 69 6e 65 01
    )
    // Method begins at RVA 0x2050
    // Code size 6 (0x6)
    .maxstack 8

    // sequence point: (line 24, col 38) to (line 24, col 50) in _
    IL_0000: call valuetype [System.Runtime]System.DateTime [System.Runtime]System.DateTime::get_Now()
    IL_0005: ret
}
// .NET 8
.method public hidebysig 
    instance valuetype [System.Runtime]System.DateTime DateTimeUtcNow () cil managed 
{
    .custom instance void [BenchmarkDotNet.Annotations]BenchmarkDotNet.Attributes.BenchmarkAttribute::.ctor(int32, string) = (
        01 00 1a 00 00 00 01 5f 00 00
    )
    // Method begins at RVA 0x2057
    // Code size 6 (0x6)
    .maxstack 8

    // sequence point: (line 27, col 41) to (line 27, col 56) in _
    IL_0000: call valuetype [System.Runtime]System.DateTime [System.Runtime]System.DateTime::get_UtcNow()
    IL_0005: ret
}

// .NET 8 (X64)
DateTimeNow()
    L0000: jmp qword ptr [0x7ffa0e065e90]
// .NET 8 (X64)
DateTimeUtcNow()
    L0000: jmp qword ptr [0x7ffa0e0667f0]


Benchmark Description:


The provided benchmark code is designed to measure and compare the performance of two common methods for retrieving the current date and time in .NET: `DateTime.Now` and `DateTime.UtcNow`. It uses BenchmarkDotNet, a powerful .NET library for benchmarking, to execute and measure the performance of these methods. The configuration and specific benchmarks are set up to provide insights into how each method performs under the same conditions, specifically focusing on execution time and memory usage. ### General Setup - **.NET Version:** The benchmark is configured to run on .NET 8, as indicated by the configuration setup where it specifies `.WithRuntime(CoreRuntime.Core80)`. This means the benchmark results will be relevant for applications running on this version of the .NET runtime. - **Configuration:** The benchmark class is decorated with a custom configuration (`Config`), which specifies the runtime and modifies the summary style. It also uses the `MemoryDiagnoser` attribute to include memory allocation diagnostics in the benchmark results. - **Columns:** Certain columns (Job, RatioSD, AllocRatio) are hidden from the output to focus the results on the most relevant information for this benchmark. ### Benchmarks #### 1. `DateTimeNow()` - **Purpose:** This method measures the performance of accessing `DateTime.Now`. This property gets the current date and time from the system's clock, adjusting for the local time zone. - **Performance Aspect:** It tests how quickly the system can retrieve the current local date and time, including the overhead of time zone adjustment. This is important because accessing the current time is a common operation in many applications, and understanding its performance characteristics can help in optimizing code that relies heavily on date and time operations. - **Expected Insights:** Running this benchmark will provide insights into the execution time and memory allocations involved in calling `DateTime.Now`. It serves as the baseline in this comparison. #### 2. `DateTimeUtcNow()` - **Purpose:** This method benchmarks the performance of `DateTime.UtcNow`, which retrieves the current date and time in Coordinated Universal Time (UTC) from the system's clock. - **Performance Aspect:** It evaluates the efficiency of fetching the current UTC date and time, which bypasses the need for local time zone adjustment. This is crucial for applications that rely on time zone-agnostic timestamps, such as logging, time-stamping events, or working with dates and times in a distributed system. - **Expected Insights:** The benchmark aims to reveal the execution time and memory allocations for calling `DateTime.UtcNow`. Since `DateTime.UtcNow` is generally expected to be faster and allocate less memory than `DateTime.Now` due to the lack of a time zone conversion, this benchmark can validate those assumptions and quantify the difference. ### Conclusion By comparing the performance of `DateTime.Now` and `DateTime.UtcNow`, developers can make informed decisions about which to use based on their specific needs regarding accuracy (local time vs. UTC) and performance (execution time and memory usage). For instance, if an application requires high performance and is not concerned with local time zones, `DateTime.UtcNow` might be the preferred choice. The insights gained from these benchmarks can guide optimizations and best practices in date and time handling within .NET applications.


Benchmark Comments: