Blame the OS / hardware. No mainstream OS can provide nano second precision timing, so adding support for it in Java was basically a useless exercise. The best you can get is microsecond precision from it. But perhaps in the future such things will become possible, who knows.
With a bit of C++ (and a JNI wrapper), we can do accurate milli/micro sleeps:
#include <time.h>
#include <errno.h>
void millisleep(const int ms)
{
struct timespec sleeptime;
struct timespec remaining;
int result;
remaining.tv_sec = (ms/1000);
remaining.tv_nsec = (ms%1000)*1000000;
do {
sleeptime.tv_sec = remaining.tv_sec;
sleeptime.tv_nsec = remaining.tv_nsec;
result = nanosleep(&sleeptime,&remaining);
} while(0>result && EINTR==errno);
}
void microsleep(const int us)
{
struct timespec sleeptime;
struct timespec remaining;
int result;
remaining.tv_sec = (us/1000000);
remaining.tv_nsec = (us%1000000)*1000;
do {
sleeptime.tv_sec = remaining.tv_sec;
sleeptime.tv_nsec = remaining.tv_nsec;
result = nanosleep(&sleeptime,&remaining);
} while(0>result && EINTR==errno);
}
I am obviously ignorant and naive, but where would you need nanosecond accuracy anyway? I already find it hard to believe that a few microseconds here or there matter. It’s an honest question, in what scenarios do you need accurate microseconds or better?
Andreas
For almost everything there is no use. There are, however, some real-time versions of Java where this may be useful. A 2 GHz processor is 0.5 nanoseconds / cycle so the unit is not meaning-less.
If there are musical parts that are off by a couple milliseconds, they definitely start to feel “out of the pocket”. At a single millisecond or less, I’d think I’d have trouble identifying parts that lead/lag. Maybe a world-class professional percussionist could sense offsets at the micro-second level, but I think even so, it would be a matter of hundreds of microseconds, not a matter of just a few.
But even with micro-second timing, it’s moot if the GC interruptions take milliseconds to complete, yes? I mean, there are issues relevent to timing besides the degree of granularity of the “getCurrentTime” function.
Concerns at the nano-level can be left to the folks at CERN.