I tested different ways of generating a timestamp when I found something surprising (to me).
Calling Windows's GetSystemTimeAsFileTime
using P/Invoke is about 3x slower than calling DateTime.UtcNow
that internally uses the CLR's wrapper for the same GetSystemTimeAsFileTime
.
How can that be?
Here's DateTime.UtcNow
's implementation:
public static DateTime UtcNow {
get {
long ticks = 0;
ticks = GetSystemTimeAsFileTime();
return new DateTime( ((UInt64)(ticks + FileTimeOffset)) | KindUtc);
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)] // Implemented by the CLR
internal static extern long GetSystemTimeAsFileTime();
Core CLR's wrapper for GetSystemTimeAsFileTime
:
FCIMPL0(INT64, SystemNative::__GetSystemTimeAsFileTime)
{
FCALL_CONTRACT;
INT64 timestamp;
::GetSystemTimeAsFileTime((FILETIME*)×tamp);
#if BIGENDIAN
timestamp = (INT64)(((UINT64)timestamp >> 32) | ((UINT64)timestamp << 32));
#endif
return timestamp;
}
FCIMPLEND;
My test code utilizing BenchmarkDotNet:
public class Program
{
static void Main() => BenchmarkRunner.Run<Program>();
[Benchmark]
public DateTime UtcNow() => DateTime.UtcNow;
[Benchmark]
public long GetSystemTimeAsFileTime()
{
long fileTime;
GetSystemTimeAsFileTime(out fileTime);
return fileTime;
}
[DllImport("kernel32.dll")]
public static extern void GetSystemTimeAsFileTime(out long systemTimeAsFileTime);
}
And the results:
Method | Median | StdDev |
------------------------ |----------- |---------- |
GetSystemTimeAsFileTime | 14.9161 ns | 1.0890 ns |
UtcNow | 4.9967 ns | 0.2788 ns |
internalcall
calling convention just like the CLR implementation, which avoids p/invoke overhead by assuming that the callee is aware of .NET memory layout and will take care of things. – Ouelletteunsafe
using a pointer, instead of anout
parameter. With a pointer, your code is responsible for performing pinning, and you can outright skip it for a stack variable. – Ouellette