www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - nanosecond time

reply ishwar <cmich.cps gmail.com> writes:
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
Feb 13 2016
next sibling parent jkpl <jkpl nowhere.fr> writes:
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
use a StopWatch:
Feb 13 2016
prev sibling parent Saurabh Das <saurabh.das gmail.com> writes:
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; } }
Feb 14 2016