bluevoxel
bluevoxel

Reputation: 5368

The method of calculating the delay between pressing the button and the execution of line of code

Is it possible to evaluate in Java/JavaFX the delay between pressing the keyboard button and the execution of the line of code? Imagine situation, where I present a stimulus to the user and its task is to hit SPACE key when he or she perceive that stimulus. How can I get most accurately the delay between display the stimulus and hitting the keyboard key?

To this day I've used something like this:

long start_time = System.currentTimeMillis();
displayTheStimulus();

long end_time;
if (spacebarIsHitted()) {
    end_time = System.currentTimeMillis();
} else {
    end_time = start_time;
}

long difference = end_time-start_time

How can I be sure, that values given by this method are valid and accurate? Is there a way to evaluate how accurate this method is?

Upvotes: 0

Views: 159

Answers (1)

AlmasB
AlmasB

Reputation: 3407

According to java System documentation, you can use System.nanoTime() to measure how long some action takes, which uses higher resolution timer (subject to availability on the underlying platform). Based on the platform you might have a slight error rate.

Furthermore since you are using JavaFX for GUI, the following is copied from this answer

According to JavaFX Architecture it uses the native event queue for capturing and batching all the events. By capturing it is understood that at that moment in time the event was generated (the user clicked the button). Taking batching into account we have already lost the information about the time the event was generated (unless JavaFX internally keeps that information, you can inspect com.sun.javafx packages for lower level details). Every 1/60th of a second there is a scheduled pulse event. During the pulse event all other JavaFX events like MouseEvent, etc. are fired via the normal JavaFX event dispatching mechanism. It is at this point that your application will receive a notification from JavaFX that an event has occurred. So in an ideal world the difference between the time an event was posted and the time it was handled should be < 0.0166(6) seconds.

In short, when the SPACE key is actually hit and when JavaFX tells you when the key was hit are different values, where difference should be < 0.0166(6) seconds. So you must take this into account. It's also worth noting that if for any reason JavaFX Application Thread gets delayed, the difference will also increase, hence greater error rate.

Upvotes: 1

Related Questions