/*
 * [TestTimerResolution.java]
 *
 * Summary: Discover the resolution/granularity of System.currentTimeMillis.
 *
 * Copyright: (c) 2013-2017 Roedy Green, Canadian Mind Products, http://mindprod.com
 *
 * Licence: This software may be copied and used freely for any purpose but military.
 *          http://mindprod.com/contact/nonmil.html
 *
 * Requires: JDK 1.8+
 *
 * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
 *
 * Version History:
 *  1.0 2013-01-16
 */
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 )
                {  /* tight loop */ }
            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();
        }
    }