低开销获取时间戳

前言

在前面文章《Cobar SQL审计的设计与实现》中提了一句关于时间戳获取性能的问题

获取操作系统时间,在Java中直接调用 System.currentTimeMillis(); 就可以,但在Cobar中如果这么获取时间,就会导致性能损耗非常严重(怎么解决?去Cobar的github仓库上看看代码吧)。

这个话题展开具体说说,我们在Java中获取时间戳的方法是System.currentTimeMillis(),返回的是毫秒级的时间戳,查看源码,注释写的比较清楚,虽然该方法返回的是毫秒级的时间戳,但精度取决于操作系统,很多操作系统返回的精度是10毫秒。

/**
     * Returns the current time in milliseconds.  Note that
     * while the unit of time of the return value is a millisecond,
     * the granularity of the value depends on the underlying
     * operating system and may be larger.  For example, many
     * operating systems measure time in units of tens of
     * milliseconds.
     *
     * <p> See the description of the class <code>Date</code> for
     * a discussion of slight discrepancies that may arise between
     * "computer time" and coordinated universal time (UTC).
     *
     * @return  the difference, measured in milliseconds, between
     *          the current time and midnight, January 1, 1970 UTC.
     * @see     java.util.Date
     */
    public static native long currentTimeMillis();

关于为什么System.currentTimeMillis()慢,有大佬写了文章详细地阐述了原因,建议仔细阅读,非常深入和详细,文章地址

http://pzemtsov.github.io/2017/07/23/the-slow-currenttimemillis.html

总结起来原因是System.currentTimeMillis调用了gettimeofday()

  • 调用gettimeofday()需要从用户态切换到内核态;
  • gettimeofday()的表现受Linux系统的计时器(时钟源)影响,在HPET计时器下性能尤其差;
  • 系统只有一个全局时钟源,高并发或频繁访问会造成严重的争用。

我们测试一下System.currentTimeMillis()在不同线程下的性能,这里使用中间件常用的JHM来测试,测试1到128线程下获取1000万次时间戳需要的时间分别是多少,这里给出在我的电脑上的测试数据:

Benchmark                    Mode  Cnt  Score   Error  Units
TimeStampTest.test1Thread    avgt       0.271           s/op
TimeStampTest.test2Thread    avgt       0.272           s/op
TimeStampTest.test4Thread    avgt       0.278           s/op
TimeStampTest.test8Thread    avgt       0.375           s/op
TimeStampTest.test16Thread   avgt       0.737           s/op
TimeStampTest.test32Thread   avgt       1.474           s/op
TimeStampTest.test64Thread   avgt       2.907           s/op
TimeStampTest.test128Thread  avgt       5.732           s/op

可以看出在1-4线程下比较快,8线程之后就是线性增长了。
测试代码参考:

@State(Scope.Benchmark)
public class TimeStampTest {

    private static final int MAX = 10000000;

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(TimeStampTest.class.getSimpleName())
                .forks(1)
                .warmupIterations(1)
                .measurementIterations(1)
                .warmupTime(TimeValue.seconds(5))
                .measurementTime(TimeValue.seconds(5))
                .mode(Mode.AverageTime)
                .syncIterations(false)
                .build();

        new Runner(opt).run();
    }

    @Benchmark
    @Threads(1)
    public void test1Thread() {
        for (int i = 0; i < MAX; i++) {
            currentTimeMillis();
        }
    }

    @Benchmark
    @Threads(2)
    public void test2Thread() {
        for (int i = 0; i < MAX; i++) {
            currentTimeMillis();
        }
    }

    @Benchmark
    @Threads(4)
    public void test4Thread() {
        for (int i = 0; i < MAX; i++) {
            currentTimeMillis();
        }
    }

    @Benchmark
    @Threads(8)
    public void test8Thread() {
        for (int i = 0; i < MAX; i++) {
            currentTimeMillis();
        }
    }

    @Benchmark
    @Threads(16)
    public void test16Thread() {
        for (int i = 0; i < MAX; i++) {
            currentTimeMillis();
        }
    }

    @Benchmark
    @Threads(32)
    public void test32Thread() {
        for (int i = 0; i < MAX; i++) {
            currentTimeMillis();
        }
    }

    @Benchmark
    @Threads(64)
    public void test64Thread() {
        for (int i = 0; i < MAX; i++) {
            currentTimeMillis();
        }
    }

    @Benchmark
    @Threads(128)
    public void test128Thread() {
        for (int i = 0; i < MAX; i++) {
            currentTimeMillis();
        }
    }

    private static long currentTimeMillis() {
        return System.currentTimeMillis();
    }
}

解法

最容易想到的方法是缓存时间戳,并使用一个独立的线程来更新它。这样获取就只是从内存中取一下,开销非常小,但缺点也很明显,更新的频率决定了时间戳的精度。

Cobar

Cobar获取和更新时间戳相关代码位于

https://github.com/alibaba/cobar/blob/master/server/src/main/server/com/alibaba/cobar/util/TimeUtil.java

/**
 * 弱精度的计时器,考虑性能不使用同步策略。
 * 
 * @author xianmao.hexm 2011-1-18 下午06:10:55
 */
public class TimeUtil {
    private static long CURRENT_TIME = System.currentTimeMillis();

    public static final long currentTimeMillis() {
        return CURRENT_TIME;
    }

    public static final void update() {
        CURRENT_TIME = System.currentTimeMillis();
    }

}

定时调度代码位于

https://github.com/alibaba/cobar/blob/master/server/src/main/server/com/alibaba/cobar/CobarServer.java

timer.schedule(updateTime(), 0L, TIME_UPDATE_PERIOD);
...
// 系统时间定时更新任务
private TimerTask updateTime() {
    return new TimerTask() {
        @Override
        public void run() {
            TimeUtil.update();
        }
    };
}

而Cobar中的更新间隔 TIME_UPDATE_PERIOD 是20毫秒

Sentinel

Sentinel也用到了缓存时间戳,其代码位于

https://github.com/alibaba/Sentinel/blob/master/sentinel-core/src/main/java/com/alibaba/csp/sentinel/util/TimeUtil.java

public final class TimeUtil {

    private static volatile long currentTimeMillis;

    static {
        currentTimeMillis = System.currentTimeMillis();
        Thread daemon = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    currentTimeMillis = System.currentTimeMillis();
                    try {
                        TimeUnit.MILLISECONDS.sleep(1);
                    } catch (Throwable e) {

                    }
                }
            }
        });
        daemon.setDaemon(true);
        daemon.setName("sentinel-time-tick-thread");
        daemon.start();
    }

    public static long currentTimeMillis() {
        return currentTimeMillis;
    }
}

可以看到Sentinel实现的是每隔1毫秒缓存一次。
我们修改一下测试代码测试一下Sentinel的实现方式在1-128线程下的性能表现

Benchmark                    Mode  Cnt   Score   Error  Units
TimeStampTest.test1Thread    avgt       ≈ 10⁻⁴           s/op
TimeStampTest.test2Thread    avgt       ≈ 10⁻⁴           s/op
TimeStampTest.test4Thread    avgt       ≈ 10⁻⁴           s/op
TimeStampTest.test8Thread    avgt       ≈ 10⁻³           s/op
TimeStampTest.test16Thread   avgt        0.001           s/op
TimeStampTest.test32Thread   avgt        0.001           s/op
TimeStampTest.test64Thread   avgt        0.003           s/op
TimeStampTest.test128Thread  avgt        0.006           s/op

可以和直接使用System.currentTimeMillis对比,差距非常明显。

最后

虽然缓存时间戳性能能提升很多,但这也仅限于非常高的并发系统中,一般比较适用于高并发的中间件,如果一般的系统来做这个优化,效果并不明显。性能优化还是要抓住主要矛盾,解决瓶颈,切忌不可过度优化。


关于作者:专注后端的中间件开发,公众号"捉虫大师"作者,关注我,给你最纯粹的技术干货

posted @ 2021-10-27 09:48  捉虫大师  阅读(308)  评论(0编辑  收藏  举报