Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

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

0 contributions
8 points

This posts try to answer for 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
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more