1

I am doing simulation project where i have hundred of CPU-Bound jobs running for 10 to 50 milliseconds. The Job is a Runnable object with specified running-time for which the job will keep CPU busy. There are 10 threads waiting in a thread pool for job arrival. I set request rate to 40 requests per second and all jobs running-time is set to 10ms. But results are so much terrible . All jobs run for at least 15ms. There is no job that runs for 10 ms. i test the experiment with jobs at 15ms and i got correct result. Why does 10ms jobs run for atleast 15ms?(I am using WINDOWS8).

public class CpuBoundJob implements Runnable {
long runningTime
     public CpuBoundJob(long runningTime) {
        this.runningTime=runningTime;
          }
    @Override
    public void run() {

         long timeToWait = this.runningTime;
         long startTime = System.currentTimeMillis();
         while(startTime + timeToWait > System.currentTimeMillis());
}
}
Faisal Bahadur
  • 498
  • 3
  • 19
  • 1
    The resolution of your system timer is probably 15ms. You could try [`System.nanoTime()`](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#nanoTime--), but it might not have any more resolution. The linked Javadoc says (in part) *no guarantees are made except that the resolution is at least as good as that of `currentTimeMillis()`.* – Elliott Frisch Nov 14 '15 at 01:39

1 Answers1

1

On many systems (Windows specifically, IIRC), System.currentTimeMillis() is backed by a clock that is only accurate to with 15 milliseconds or so.

However, it's even worse: System.currentTimeMillis() measures time since the Unix epoch as measured by your system clock. So if you change the time on your computer (e.g. due to syncing your system clock to a time source, or due to a leap second, or any number of other things) then currentTimeMillis() can jump forward or backward arbitrarily large amounts of time.

If you want to measure elapsed time, NEVER use currentTimeMillis(). Use System.nanoTime() instead. As a bonus, on most systems, it's also substantially cheaper to invoke and substantially more accurate.

Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135
  • i have used System.nanoTime() which gives worse results than System.currentTimeMillis() . Some jobs even run for 0ms when System.nanoTime() is used. – Faisal Bahadur Nov 14 '15 at 02:01
  • @MuhammadAbdullah When nano time has a resultion of 15ms as well, then jumping from 0 to 15 will happen at some point with that clock source. If you're unlucky it's the moment between recording startTime and checking in the loop. Results in effectively 0 wait time but there is nothing you could do about. Ps when testing `nanoTime`, you made sure to multiply your wait time by 1000000? – zapl Nov 14 '15 at 02:26
  • @MuhammadAbdullah: On Windows 8, `nanoTime()` should have substantially better resolution. Can you show the code where that's not the case? – Daniel Pryden Nov 14 '15 at 04:57