Home arrow static arrow Java Programming [Archive] - Java timing and accuracy
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Java timing and accuracy
This topic has 7 replies on 1 page.

Posts:21
Registered: 9/25/03
Java timing and accuracy  
Jun 29, 2004 12:36 PM



 
I have a small script that runs a loop with a specified sleep/pause time,
For each loop a start and end time is logged.

I am trying to figure out how accurate the timing is for each loop iteration
I have found that the longer the loop runs the longer it sometimes takes to finish one iteration.
Does anyone know why this is? Can anyone shed some light on why this happens?

I have a sample test script that runs from the command line
$ java test
Usage: java test [loops] [sleeptime] [delaytolerance]
Some tests I have used are
java test 10000 2 10 (passes regularly)
java test 100000 2 10 (fails regularly, at random iterations)
java test 10000 5 10 (fails sometimes at random iterations like 205, 2009, 7723)

The test runs "loops" times, and sleeps for "sleeptime" each iteration.
When the "delaytolerance" is exceeded an error is printed out, otherwise the program ends quietly.

Any insight would be greatly appreciated!
Below is the source code for the class test used for testing:
public class test{  public static int STATUS_SUCCESS = 0;  public static int STATUS_FAILURE = 1;   public static void main(String[] args)  {    if (args.length != 3)    {      System.out.println("Usage: java test [loops] [sleeptime] [delaytolerance]");      return;    }     test(Integer.parseInt(args[0]), Integer.parseInt(args[1]), Integer.parseInt(args[2]));   }   public static int test(long plLoopMax, long plSleepTime, long plDelayTolerance)  {    long lStartTime, lEndTime;     for (int i=0; i < plLoopMax; i++)    {      lStartTime = System.currentTimeMillis();      try { Thread.sleep(plSleepTime); } catch (Exception e) {}      lEndTime = System.currentTimeMillis();       if ((lEndTime - lStartTime - plSleepTime) > plDelayTolerance)      {        System.out.println("Failed at iteration = " + i);        System.out.println(lStartTime + " - " + lEndTime + " - " + plSleepTime + " = " + (lEndTime-lStartTime-plSleepTime));	return STATUS_FAILURE;      }    }     return STATUS_SUCCESS;  } }
 

Posts:487
Registered: 11/19/97
Re: Java timing and accuracy  
Jun 29, 2004 1:14 PM (reply 1 of 7)



 
The first important clue we get is by reading the documentation for System.currentTimeMillis():
"Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger.
So timing using System.currentTimeMillis() is not entirely accurate. Thread.sleep(ms) probably suffers from the same issue.

The second importand fact is that the JVM does things like garbage collect, and optimize code, which take time and affect how fast code runs.

The third importand fact is that the operating system that the JVM is running on, is probably juggling dozens to hundreds of processes/threads/tasks. The rate at which the operating system gives resources to your program will affect how many operations it can perform in any slice of time.
 

Posts:5
Registered: 6/1/98
Re: Java timing and accuracy  
Jun 29, 2004 1:14 PM (reply 2 of 7)



 
Unfortunately your levels of granularity are not compatible. Your sleep method is fine, but your use of the Java System.currentTimeMillis() is flawed by JDK reliance on the PC clock rather than the use of a high performance timer. The System.currentTimeMillis() only has a granularity of about 10 milliseconds and you are trying to compare it against sleep times with single millisecond accuracy. So in fact there may be many instances where your test should be failing because the actual time difference was 10.1 to 19.9 milliseconds, but since the System timer runs in 10 second intervals, your tests will really only fail if it sleeps for over 20 milliseconds.
I think if you changed your sleep times to be an order of 10milliseconds intervals or had the ability to use a high resolution timer (not System.currentTimeMillis()) you would see much more consisten failures in test. As for why this happens I think it is pretty simple to understand that other applications are running and sometimes have a higher priority than what is needed to awake your jave thread that is sleeping.

Hope this helps,

Dave
 

Posts:21
Registered: 9/25/03
Re: Java timing and accuracy  
Jun 29, 2004 1:34 PM (reply 3 of 7)



 
Thanks for the replies...
I guess I cannot rely on the the System.currentTimeMillis() for accuracy.
Is it a lost cause to use Java for a time critical application if I cannot rely on the accuracy of the System.currentTimeMillis(), as well as the JVM?
 

Posts:487
Registered: 11/19/97
Re: Java timing and accuracy  
Jun 29, 2004 1:52 PM (reply 4 of 7)



 
What do you mean by "time critical"?
Do you mean "responsive" to a user? General number crunching?
Then, no, it is not a lost cause to use Java.

Do you mean Real Time?
Then a simple search offers a lot of information.
http://www.google.ca/search?q=real+time+java&ie=UTF-8&hl=en&btnG=Google+Search&meta=
 

Posts:5
Registered: 6/1/98
Re: Java timing and accuracy  
Jun 29, 2004 1:52 PM (reply 5 of 7)



 
You can rely on it as long as you are not looking for a level of detail lower than 10 milliseconds when you are using System.currentTImeMillis(). The Thread.sleep() method should perform quite accurately at a much higher resolution than System.currentTImeMillis(). You could also wrap some native code to use timers if necessary or use a 3rd party high resolution product (although this will rely on JNI as well).

Good luck

Dave
[url=http://www.davehensley.com]java[/url]
[url=http://www.davehensley.com]http://www.davehensley.com[/url]
 

Posts:1,160
Registered: 7/24/97
Re: Java timing and accuracy  
Jun 30, 2004 1:48 AM (reply 6 of 7)



 
In addition to the insights provided by the previous posters there is something else which needs to be taken into consideration.

There is no guarantee that a Thread will become the running Thread immediately after its sleep
period is completed. It is only available to become the running Thread, other Threads may have priority
over it and will run first and the currently running Thread will not normally be preempted by the Thread
whose sleep/wait time has come to an end.
 

Posts:21
Registered: 9/25/03
Re: Java timing and accuracy  
Jun 30, 2004 7:33 AM (reply 7 of 7)



 
Mgbolusm, I have provided a PC environment by which developers can write scripts to send and receive messages to an external device. The scripts are for feature testing and regression testing, so it is common for a script to send a message and expect a response within a certain "expiration" time.

If it receives the response the test passes and may continue, if the response does not arrive prior to the expire time then the test should fail. For these scripts timing and accuracy is important. The problem is if I am accumulating and storing the sent/received messages in buffers then as the buffers grow, it sounds like the JVM's runtime timing and accuracy will degrade as the buffer size grows. Hence my dilemna.

In response to dhensley, if my buffers grow large (obviously a bad design but for the sake of an example) then 10ms may sometimes turn to 50ms or even 100ms if garbage collection takes place on the unused portions of my buffers (arrays of strings or vectors of strings).

I'll need to look into it more but perhaps javax.realtime may be the answer to all my needs,
Thanks again!
 
This topic has 7 replies on 1 page.