System.nanoTime与System.currentTimeMillis

时间:2014-01-01 23:10:27

标签: java multithreading nanotime

根据其文档,System.nanoTime返回 纳秒,因为某些固定但任意的原始时间。但是,在所有x64机器上我尝试了下面的代码,有时间跳转,移动固定原点时间。我的方法可能存在一些缺陷,使用替代方法(此处为currentTimeMillis)获取正确的时间。但是,测量相对时间(持续时间)的主要目的也会受到负面影响。

我遇到了这个问题,试图在将不同的队列与LMAX的Disruptor进行比较时测量延迟,有时我会得到非常负的延迟。在这些情况下,开始和结束时间戳是由不同的线程创建的,但延迟是在这些线程完成后计算的。

我的代码在这里花费时间使用nanoTime,计算currentTimeMillis时间中的固定原点,并比较调用之间的原点。因为我必须在这里提出一个问题:这段代码有什么问题?为什么会发现违反固定来源合同?或者不是吗?

import java.text.*;

/**
 * test coherency between {@link System#currentTimeMillis()} and {@link System#nanoTime()}
 */
public class TimeCoherencyTest {

    static final int MAX_THREADS = Math.max( 1, Runtime.getRuntime().availableProcessors() - 1);
    static final long RUNTIME_NS = 1000000000L * 100;
    static final long BIG_OFFSET_MS = 2;

    static long startNanos;
    static long firstNanoOrigin;
    static {
        initNanos();
    }

    private static void initNanos() {
        long    millisBefore = System.currentTimeMillis();
        long    millisAfter;
        do {
            startNanos = System.nanoTime();
            millisAfter = System.currentTimeMillis();
        } while ( millisAfter != millisBefore);
        firstNanoOrigin = ( long) ( millisAfter - ( startNanos / 1e6));
    }

    static NumberFormat lnf = DecimalFormat.getNumberInstance();
    static {
        lnf.setMaximumFractionDigits( 3);
        lnf.setGroupingUsed( true);
    };

    static class TimeCoherency {
        long    firstOrigin;
        long    lastOrigin;
        long    numMismatchToLast = 0;
        long    numMismatchToFirst = 0;
        long    numMismatchToFirstBig = 0;
        long    numChecks = 0;

        public TimeCoherency( long firstNanoOrigin) {
            firstOrigin = firstNanoOrigin;
            lastOrigin = firstOrigin;
        }
    }

    public static void main( String[] args) {
        Thread[]    threads = new Thread[ MAX_THREADS];
        for ( int i = 0;  i < MAX_THREADS;  i++) {
            final int   fi = i;
            final TimeCoherency tc = new TimeCoherency( firstNanoOrigin);
            threads[ i] = new Thread() {
                @Override
                public void run() {
                    long    start = getNow( tc);
                    long    firstOrigin = tc.lastOrigin;    // get the first origin for this thread
                    System.out.println( "Thread " + fi + " started at " + lnf.format( start) + " ns");
                    long    nruns = 0;
                    while ( getNow( tc) < RUNTIME_NS) {
                        nruns++;
                    }
                    final long  runTimeNS = getNow( tc) - start;
                    final long  originDrift = tc.lastOrigin - firstOrigin;
                    nruns += 3; // account for start and end call and the one that ends the loop
                    final long skipped = nruns - tc.numChecks;
                    System.out.println( "Thread " + fi + " finished after " + lnf.format( nruns) + " runs in " + lnf.format( runTimeNS) + " ns (" + lnf.format( ( double) runTimeNS / nruns) + " ns/call) with"
                            + "\n\t" + lnf.format( tc.numMismatchToFirst) + " different from first origin (" + lnf.format( 100.0 * tc.numMismatchToFirst / nruns) + "%)"
                            + "\n\t" + lnf.format( tc.numMismatchToLast) + " jumps from last origin (" + lnf.format( 100.0 * tc.numMismatchToLast / nruns) + "%)"
                            + "\n\t" + lnf.format( tc.numMismatchToFirstBig) + " different from first origin by more than " + BIG_OFFSET_MS + " ms"
                                    + " (" + lnf.format( 100.0 * tc.numMismatchToFirstBig / nruns) + "%)"
                            + "\n\t" + "total drift: " + lnf.format( originDrift) + " ms, " + lnf.format( skipped) + " skipped (" + lnf.format( 100.0 * skipped / nruns) + " %)");
                }};
            threads[ i].start();
        }
        try {
            for ( Thread thread : threads) {
                thread.join();
            }
        } catch ( InterruptedException ie) {};
    }

    public static long getNow( TimeCoherency coherency) {
        long    millisBefore = System.currentTimeMillis();
        long    now = System.nanoTime();
        if ( coherency != null) {
            checkOffset( now, millisBefore, coherency);
        }
        return now - startNanos;
    }

    private static void checkOffset( long nanoTime, long millisBefore, TimeCoherency tc) {
        long    millisAfter = System.currentTimeMillis();
        if ( millisBefore != millisAfter) {
            // disregard since thread may have slept between calls
            return;
        }
        tc.numChecks++;
        long    nanoMillis = ( long) ( nanoTime / 1e6);
        long    nanoOrigin = millisAfter - nanoMillis;
        long    oldOrigin = tc.lastOrigin;
        if ( oldOrigin != nanoOrigin) {
            tc.lastOrigin = nanoOrigin;
            tc.numMismatchToLast++;
        }
        if ( tc.firstOrigin != nanoOrigin) {
            tc.numMismatchToFirst++;
        }
        if ( Math.abs( tc.firstOrigin - nanoOrigin) > BIG_OFFSET_MS) {
            tc.numMismatchToFirstBig ++;
        }
    }
}

现在我做了一些小改动。基本上,我将nanoTime调用括在两个currentTimeMillis调用之间,以查看该线程是否已被重新调度(这应该超过currentTimeMillis分辨率)。在这种情况下,我忽略了循环周期。实际上,如果我们知道nanoTime足够快(就像像Ivy Bridge这样的新架构),我们可以将currentTimeMillis括在nanoTime中。

现在长> 10ms的跳跃消失了。相反,我们计算每个线程距离第一个原点超过2毫秒的时间。在我测试过的机器上,对于100s的运行时间,调用之间总会有接近200,000次跳转。对于那些我认为currentTimeMillis或nanoTime可能不准确的情况。

2 个答案:

答案 0 :(得分:4)

如前所述,每次计算新的来源都意味着你会遇到错误。

//                               ______ delay _______
//                              v                    v
long origin = (long)(System.currentTimeMillis() - System.nanoTime() / 1e6);
//                                                                  ^
//                                                            truncation

如果您修改程序以便计算原点差异,您会发现它非常小。我测量的平均值大约为200ns,这对于延时来说是正确的。

使用乘法而不是除法(这应该没有溢出再过几百年)你还会发现计算的未通过相等性检查的起源数量要大得多,大约为99%。如果错误的原因是由于时间延迟,它们只会在延迟恰好与最后一个相同时通过。

一个更简单的测试是累计经过一段时间后对nanoTime的调用所花费的时间,看看它是否用第一次和最后一次调用结账:

public class SimpleTimeCoherencyTest {
    public static void main(String[] args) {
        final long anchorNanos = System.nanoTime();

        long lastNanoTime = System.nanoTime();
        long accumulatedNanos = lastNanoTime - anchorNanos;

        long numCallsSinceAnchor = 1L;

        for(int i = 0; i < 100; i++) {
            TestRun testRun = new TestRun(accumulatedNanos, lastNanoTime);

            Thread t = new Thread(testRun);
            t.start();

            try {
                t.join();
            } catch(InterruptedException ie) {}

            lastNanoTime = testRun.lastNanoTime;
            accumulatedNanos = testRun.accumulatedNanos;
            numCallsSinceAnchor += testRun.numCallsToNanoTime;
        }

        System.out.println(numCallsSinceAnchor);
        System.out.println(accumulatedNanos);
        System.out.println(lastNanoTime - anchorNanos);
    }

    static class TestRun
    implements Runnable {
        volatile long accumulatedNanos;
        volatile long lastNanoTime;
        volatile long numCallsToNanoTime;

        TestRun(long acc, long last) {
            accumulatedNanos = acc;
            lastNanoTime = last;
        }

        @Override
        public void run() {
            long lastNanos = lastNanoTime;
            long currentNanos;

            do {
                currentNanos = System.nanoTime();
                accumulatedNanos += currentNanos - lastNanos;
                lastNanos = currentNanos;
                numCallsToNanoTime++;
            } while(currentNanos - lastNanoTime <= 100000000L);

            lastNanoTime = lastNanos;
        }
    }
}

该测试确实表明原点是相同的(或至少错误是零均值)。

答案 1 :(得分:0)

据我所知,方法System.currentTimeMillis()确实有时会跳转,取决于底层操作系统。我有时会观察到这种行为。

因此,您的代码给我的印象是您尝试重复System.nanoTime()System.currentTimeMillis()之间的偏移。您应该通过仅调用System.currentTimeMillis()一次来尝试观察此偏移,然后才能说System.nanoTimes()有时会导致跳转。

顺便说一句,我不会假装规范(javadoc描述System.nanoTime()与某个固定点相关)总是完美实现。您可以查看此discussion,其中多核CPU或CPU频率的变化会对System.nanoTime()的所需行为产生负面影响。但有一件事是肯定的。 System.currentTimeMillis()更容易受到任意跳跃的影响。