前言
在前面文章《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 UnitsTimeStampTest.test1Thread avgt 0.271 s/opTimeStampTest.test2Thread avgt 0.272 s/opTimeStampTest.test4Thread avgt 0.278 s/opTimeStampTest.test8Thread avgt 0.375 s/opTimeStampTest.test16Thread avgt 0.737 s/opTimeStampTest.test32Thread avgt 1.474 s/opTimeStampTest.test64Thread avgt 2.907 s/opTimeStampTest.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 UnitsTimeStampTest.test1Thread avgt ≈ 10⁻⁴ s/opTimeStampTest.test2Thread avgt ≈ 10⁻⁴ s/opTimeStampTest.test4Thread avgt ≈ 10⁻⁴ s/opTimeStampTest.test8Thread avgt ≈ 10⁻³ s/opTimeStampTest.test16Thread avgt 0.001 s/opTimeStampTest.test32Thread avgt 0.001 s/opTimeStampTest.test64Thread avgt 0.003 s/opTimeStampTest.test128Thread avgt 0.006 s/op
复制代码
可以和直接使用 System.currentTimeMillis 对比,差距非常明显。
最后
虽然缓存时间戳性能能提升很多,但这也仅限于非常高的并发系统中,一般比较适用于高并发的中间件,如果一般的系统来做这个优化,效果并不明显。性能优化还是要抓住主要矛盾,解决瓶颈,切忌不可过度优化。
欢迎关注我的公众号
评论