package com.mindprod.example;
import static java.lang.System.*;
/**
* Discover the resolution/granularity of System.currentTimeMillis.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2013-01-16
* @since 2013-01-16
*/
public final class TestTimerResolution
{
/**
* how many trial to average results over
*/
private static final int TRIALS = 5000;
/**
* test resolution of System.currentTimeMillis without sleep
*/
private static void testCurrentTimeMillisNoSleep()
{
long total = 0;
for ( int i = 0; i < TRIALS; i++ )
{
final long start = System.currentTimeMillis();
long now;
while ( ( now = System.currentTimeMillis() ) == start )
{ }
total += ( now - start );
}
out.println( ( ( double ) total / ( double ) TRIALS ) + " milliseconds resolution without sleep" );
}
/**
* test resolution of System.currentTimeMillis with sleep
*/
private static void testCurrentTimeMillisWithSleep()
{
long total = 0;
for ( int i = 0; i < TRIALS; i++ )
{
final long start = System.currentTimeMillis();
long now;
while ( ( now = System.currentTimeMillis() ) == start )
{
try
{
Thread.sleep( 0 );
}
catch ( InterruptedException e )
{
}
}
total += ( now - start );
}
out.println( ( ( double ) total / ( double ) TRIALS ) + " milliseconds resolution with sleep" );
}
/**
* Discover the resolution/granularity of System.currentTimeMillis.
*
* @param args not used
*/
public static void main( String[] args )
{
testCurrentTimeMillisNoSleep();
testCurrentTimeMillisWithSleep();
}
}