开发者

java- timing the execution of a block of code

hi i want a block of code(certain lines of a function) that will run for a stipulated amount of time (say x milliseconds).Is is possible 开发者_运维技巧to do this in java?


1st approach:

long startTime = System.nanoTime();
while(System.nanoTime() - startTime < MAX_TIME_IN_NANOSECONDS){
   // your code ...
}

2nd approach

Start your code in thread.

Sleep main thread for as long as you need.

Kill (stop, interrupt) your thread.


either use an exit condition based on current timestamp, or create a separate thread and kill it after a specified timeout.


Run your method in a separate thread, but passing it to an Executor. You can then use the Future to wait a certain period of time for the the thread to complete. If it doesn't complete, you will get a TimeoutException and you can then cancel the thread. Cancelling the thread causes the thread to be interrupted. So your code will have to periodically check the thread's interrupted status and exit if necessary.

For example:

ExecutorService exec = Executors.newSingleThreadExecutor();
Future<Integer> future = exec.submit(new Callable<Integer>(){
    @Override
    public Integer call() throws Exception {

        //do some stuff

        //periodically check if this thread has been interrupted
        if (Thread.currentThread().isInterrupted()) {
            return -1;
        }                    

        //do some more stuff

        //check if interrupted
        if (Thread.currentThread().isInterrupted()) {
            return -1;
        }

        //... and so on

        return 0;
    }
});
exec.shutdown();

try {
    //wait 5 seconds for the task to complete.
    future.get(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
} catch (TimeoutException e) {
    //the task did not complete in 5 seconds
    e.printStackTrace();
    System.out.println("CANCELLING");

    //cancel it
    future.cancel(true); //sends interrupt
}


You could use Calendar:

timeInMilis = Calendar.getInstance().getTimeInMillis();
while(Calendar.getInstance().getTimeInMilis() - timeInMilis < MAX_TIME_IN_MILIS){
    // Execute block
}


Check the time using System.currentTimeMillis() and exit your loop after the time has passed.

long endTime = System.currentTimeMillis() + ClassName.EXECUTION_TIME_MS;
while (System.currentTimeMillis() < endTime) {
  // do your stuff
}

If you need to sleep inside the thread for some reason, adjust your sleep time to end at the end time.

  long timeLeft = endTime - System.currentTimeMillis();
  if (sleepAmount > timeLeft)
    sleepAmount = timeLeft;
  Thread.sleep(sleepAmount);

If you're going to use the wait() and notify() method, then use the calculated timeLeft as the argument to wait() to ensure the maximum wait time. Once that wait time hits, the method will return and the loop will break.

  long timeLeft = endTime - System.currentTimeMillis();
  if (timeLeft > 0)
    this.wait(timeLeft);

If you're running multiple steps inside the loop which can take a long time, you should add additional checks between steps, if you want the process to break between steps, to exit the loop if the designated time has passed. This is a design decision. When the timer expires, do you want the task to finish up the step it's working on and then exit? It's up to you how to code it based on the desired result.

long endTime = System.currentTimeMillis() + ClassName.EXECUTION_TIME_MS;
while (System.currentTimeMillis() < endTime) {
  this.doFirstLongThing();
  if (System.currentTimeMillis() >= endTime) break;
  this.doSecondLongThing();
  if (System.currentTimeMillis() >= endTime) break;
  this.doThirdLongThing();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜