Languages
[Edit]
EN

C# / .NET - get current machine time in nanoseconds

11 points
Created by:
Dharman
518

This posts is an answer for a common question:

How to get java System.nanoTime() in C# / .NET? 

It is possible in following way.

Getting nano time with Stopwatch.GetTimestamp method example

using System.Diagnostics;

public static class TimeUtils
{
	public static long GetNanoseconds()
	{
		double timestamp = Stopwatch.GetTimestamp();
		double nanoseconds = 1_000_000_000.0 * timestamp / Stopwatch.Frequency;

		return (long)nanoseconds;
	}
}

Example:

long t1 = TimeUtils.GetNanoseconds();

Thread.Sleep(1000);

long t2 = TimeUtils.GetNanoseconds();
long dt = t2 - t1;

Console.WriteLine(t2 + " - " + t1 + " = " + dt + " ns");

Output:

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.

References

  1. Stopwatch.GetTimestamp Method - Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join