1st approach:
long startTime = System.nanoTime(); while(System.nanoTime() - startTime < MAX_TIME_IN_NANOSECONDS){ // your code ... long estimatedTime = System.nanoTime() - startTime; } 2nd approach
Start your code in thread.
Sleep main thread for as long as you need.
Kill (stop, interrupt) your thread.