C# DateTime Performance Class

Performance optimization

Your program uses DateTime.Now to frequently capture the current time, but you wonder if there is a way to optimize this. Use a custom class to improve DateTime performance. You can cache the DateTime value for Now, improving performance significantly at the cost of accuracy, using the C# language.

Getting current time performance

DateTimeNowCache:  16.5 ns
DateTime.Now:     264.8 ns

This C# performance class optimizes accesses to the DateTime.Now method.

Example

Here we see a static utility class in C# that you can use to throttle the number of times the system is queried for the current DateTime. In the class, the constant 20 is used, which means the DateTime is only updated 5% of the time.

Program that caches DateTime instances [C#]

using System;

/// <summary>
/// Utility class to return new DateTimes every few requests.
/// </summary>
public static class DateTimeNowCache
{
    /// <summary>
    /// Refresh time after this many requests.
    /// </summary>
    const int _count = 20;

    /// <summary>
    /// The most recent time collected.
    /// </summary>
    static DateTime _recentTime = DateTime.Now;

    /// <summary>
    /// Number of skipped time collections
    /// </summary>
    static int _skipped;

    /// <summary>
    /// Get the DateTime within the last N calls.
    /// </summary>
    /// <returns>Recent DateTime collected.</returns>
    public static DateTime GetDateTime()
    {
	_skipped++;
	if (_skipped > _count)
	{
	    _recentTime = DateTime.Now;
	    _skipped = 0;
	}
	return _recentTime;
    }
}

Description. The class uses internal accounting to "throttle" the number of times the DateTime is updated. Therefore, using GetDateTime() will be around 20x faster than DateTime.Now, but less "current" 95% of the time.

Benchmark

Performance optimization

If you inspect DateTime.Now in IL Disassembler, you will see that it internally calls many methods and probably executes hundreds or more lines of code. Eventually, DateTime.Now queries the Windows operating system. System calls like this are often quite slow compared to other managed code. This benchmark shows the above DateTimeNowCache code being used in a tight loop.

IL Disassembler Tutorial Intermediate Language
Notes on benchmark

Iterations: 10000000

Code compared

DateTime now = DateTimeNowCache.GetDateTime();
DateTime now = DateTime.Now;

Benchmark results. Here, the DateTime cache code is about 94% faster. This indicates that the time required for the logic inside the DateTimeNowCache class is miniscule compared to system query. Where you would use DateTime.Now as the value you are getting, you can use DateTimeNowCache.GetDateTime() instead, as shown in the second tight loop above.

When is this code useful?

Question and answer

The code here is useful in applications that frequently query the time and service many requests in small amounts of time. For example, if you record traffic on your website, you can use this to improve performance. The times reported may be a few seconds outdated. Do not use it if the time is critical to your application.

Alternative

Programming tip

A more reliable approach to this problem could be implemented as follows. A static DateTime field exists. A static Timer instance updates the DateTime every several seconds. Code that needs the current time, then, simply accesses the static DateTime field, which is periodically updated.

Timer Tutorial

Summary

The C# programming language

Here we saw a simple way to avoid recalculating the time and querying the operating system repeatedly. In some applications, this can measurably improve performance, as it reduces the number of interop calls to the OS. You can use this class to cache the DateTimes.

Time Representations
.NET