Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent to System.nanoTime() in .NET?

Tags:

The title is pretty much self-explanatory, I'm killing myself over this simplicity.

Looked here, but it isn't much helpful.

like image 869
Lazlo Avatar asked Oct 11 '09 20:10

Lazlo


People also ask

What is System nanoTime ()?

nanoTime() method returns the current value of the most precise available system timer, in nanoseconds. The value returned represents nanoseconds since some fixed but arbitrary time (in the future, so values may be negative) and provides nanosecond precision, but not necessarily nanosecond accuracy.

Is system nanoTime () reliable?

nanoTime() is a great function, but one thing it's not: accurate to the nanosecond. The accuracy of your measurement varies widely depending on your operation system, on your hardware and on your Java version. As a rule of thumb, you can expect microsecond resolution (and a lot better on some systems).

What does nanoTime return?

nanoTime. Returns the current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds. This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.


2 Answers

I think that the Stopwatch class is what you are looking for.

like image 190
Guffa Avatar answered Sep 18 '22 21:09

Guffa


If you want a timestamp to be compared between different processes, different languages (Java, C, C#), under GNU/Linux and Windows (Seven at least):

Java:

java.lang.System.nanoTime();

C GNU/Linux:

static int64_t hpms_nano() {
   struct timespec t;
   clock_gettime( CLOCK_MONOTONIC, &t );
   int64_t nano = t.tv_sec;
   nano *= 1000;
   nano *= 1000;
   nano *= 1000;
   nano += t.tv_nsec;
   return nano;
}

C Windows:

static int64_t hpms_nano() {
   static LARGE_INTEGER ticksPerSecond;
   if( ticksPerSecond.QuadPart == 0 ) {
      QueryPerformanceFrequency( &ticksPerSecond );
   }
   LARGE_INTEGER ticks;
   QueryPerformanceCounter( &ticks );
   uint64_t nano = ( 1000*1000*10UL * ticks.QuadPart ) / ticksPerSecond.QuadPart;
   nano *= 100UL;
   return nano;
}

C#:

private static long nanoTime() {
   long nano = 10000L * Stopwatch.GetTimestamp();
   nano /= TimeSpan.TicksPerMillisecond;
   nano *= 100L;
   return nano;
}
like image 30
Aubin Avatar answered Sep 19 '22 21:09

Aubin