EN
C# / .NET - get current machine time in nanoseconds
11 points
This posts is an answer for a common question:
How to get java System.nanoTime()
in C# / .NET?
It is possible in following way.
xxxxxxxxxx
1
using System.Diagnostics;
2
3
public static class TimeUtils
4
{
5
public static long GetNanoseconds()
6
{
7
double timestamp = Stopwatch.GetTimestamp();
8
double nanoseconds = 1_000_000_000.0 * timestamp / Stopwatch.Frequency;
9
10
return (long)nanoseconds;
11
}
12
}
Example:
xxxxxxxxxx
1
long t1 = TimeUtils.GetNanoseconds();
2
3
Thread.Sleep(1000);
4
5
long t2 = TimeUtils.GetNanoseconds();
6
long dt = t2 - t1;
7
8
Console.WriteLine(t2 + " - " + t1 + " = " + dt + " ns");
Output:
xxxxxxxxxx
1
193915543540248 - 193914543003928 = 1000536320 ns
Notes:
Stopwatch.GetTimestamp
returns time from timer mechanism - system up time.- The best application of this time could be measuring how much time took some operations.