Instrumentation with nanosecond accuracy

Can anyone recommend instrumentation with nanosecond (or as accurate as possible) accuracy. The events I am timing occur in < 1ms, so I know measuring execution time probably isn't the best way to go about this, but it's what I have to work with.

At the moment, I'm using System.nanoTime() and inserting that value into a static array, which leads me to my second question: Can someone give me information on, or point me in the direction of information on, accessing static data structures vs something like a singleton?

System.nanoTime() is a good start. Depending on the hardware and the OS, the values may report actual times. In other words, one billion nanos will actually represent one second. Otherwise, they should consistently represent some fraction of a second, such as .95 or 1.05. I suggest running a test for one minute using nanoTime() and currentTimeMillis() to get a comparison.

You can access static fields and methods from any object through the Class. Note that Java doesn't do data structures. Access through a singleton requires a reference to the singleton, which is typically obtained through a static method. I suspect the performance difference is minimal.

If you are wanting to collect start and end times for a number of events, you could create a simple class that contains final startNanos and endNanos fields. For each event, get the start and end nanos, pass the values in the constructor, and then store the instance in an ArrayList. This approach allows you to store additional information for each event, such as a description. If you are tracking multiple events, this approach makes sense.

What you describe is pretty close to my current implementation, so that's reassuring.

By data structures I meant an array / arraylist. I'm currently using a 2 dimensional array storing a number of start and end times. Your addition of a class to store the times and additional detail had crossed my mine, but my concern is the time required to instantiate objects and so on would further skew timings. That probably should be the least of my worries at the minute (considering background processes etc).

Anyway, thanks again. It's good to know that someone else would do something similar to what I have planned.

... but my concern is the time required to instantiate objects and so on would further skew timings.

In Java, everything is an object except primitive types. Arrays are actually objects as well (which is what makes java overflow safe), so you're really not saving yourself anything by using arrays rather than more fully featured collections.

Note, too, that I suggested running the instrumented code and collecting the start and end nanos using primitive variables, and then instantiating a class to hold the results. Instrumentation will make the application slightly slower overall, but that approach avoids any impact of the code path being measured.