nanosecond time

Saurabh Das via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Feb 14 20:05:08 PST 2016


On Saturday, 13 February 2016 at 19:24:44 UTC, ishwar wrote:
> I am stumped on need finding interval between two events in a 
> program execution  in nanoseconds. Any sample code will be 
> appreciated (along with imports needed to make it work):
> - time in nanoseconds-now
> - do-some processing
> - time in nano-second-now
>
> Thanks

As suggested above, use a StopWatch.

I use this (not-very-cross-platform) function for latency 
measurement purposes. It is precise on Linux. For Mac OS and 
Windows, it's returns an approximation:

version(linux)  import core.sys.linux.time;
version(OSX)    import core.time;
version(Windows) import core.sys.windows.windows;

static if(is(typeof(clockid_t)))
{
     extern(C) nothrow int clock_gettime(clockid_t, timespec*);
}

public ulong getLocalTimestampNS() nothrow @nogc
{
     static if(is(typeof(clock_gettime)))
     {
         timespec ts;
         clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
         return ts.tv_sec * 1000000000 + ts.tv_nsec;
     }
     static if(is(typeof(mach_absolute_time)))
     {
         // IMPORTANT NOTE: mach_absolute_time does not always 
return nanoseconds.
         // Sometimes it returns other values. We are using it 
here as an approximation.
         return mach_absolute_time();
     }
     version (Windows)
     {
         // Just an approximation
         long cnt;
         if (QueryPerformanceCounter(&cnt))
         {
             return cnt * 500;
         }
         return 0;
     }
}



More information about the Digitalmars-d-learn mailing list