package com.epickrram.blog.nanotiming;

import org.HdrHistogram.Histogram;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

public final class TimingJob implements Runnable
{
    private static final long HIGHEST_TRACKABLE_VALUE = TimeUnit.MILLISECONDS.toNanos(10L);

    private final Histogram histogram = new Histogram(HIGHEST_TRACKABLE_VALUE, 2);

    @Override
    public void run()
    {
        long lastReportedNanos = 0L;
        final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME;
        while(!Thread.currentThread().isInterrupted())
        {
            final long startNanos = System.nanoTime();
            final long endNanos = System.nanoTime();

            histogram.recordValue(Math.min(HIGHEST_TRACKABLE_VALUE, endNanos - startNanos));

            if(endNanos > lastReportedNanos + TimeUnit.SECONDS.toNanos(1L))
            {
                if(lastReportedNanos != 0)
                {
                    System.out.printf("%s avg. time between calls to System.nanoTime() %dns%n",
                            formatter.format(LocalTime.now()), (long) histogram.getMean());
                }

                lastReportedNanos = endNanos;
                histogram.reset();
            }
        }
    }
}

@@ -69,16 +69,100 @@
 ogram;%0A%0A
+import java.io.IOException;%0Aimport java.nio.file.Files;%0Aimport java.nio.file.Paths;%0A
 import j
@@ -181,16 +181,16 @@
 alTime;%0A
-
 import j
@@ -405,16 +405,147 @@
 os(10L);
+%0A    private static final String CURRENT_CLOCKSOURCE_FILENAME = %22/sys/devices/system/clocksource/clocksource0/current_clocksource%22;
 %0A%0A    pr
@@ -1180,16 +1180,16 @@
 s != 0)%0A
-
         
@@ -1190,32 +1190,420 @@
               %7B%0A
+                    try%0A                    %7B%0A                        System.out.printf(%22Current clocksource is: %25s%25n%22, Files.readAllLines(Paths.get(CURRENT_CLOCKSOURCE_FILENAME)).get(0));%0A                    %7D%0A                    catch (IOException e)%0A                    %7B%0A                        System.err.printf(%22Failed to read current clocksource from %25s%25n%22);%0A                    %7D%0A
                 

print value of current clocksource when reporting nanoTime call latency