前言
在前面文章《Cobar SQL审计的设计与实现》中提了一句关于时间戳获取性能的问题
获取操作系统时间,在Java中直接调用 System.currentTimeMillis(); 就可以,但在Cobar中如果这么获取时间,就会导致性能损耗非常严重(怎么解决?去Cobar的github仓库上看看代码吧)。
这个话题展开具体说说,我们在Java中获取时间戳的方法是System.currentTimeMillis(),返回的是毫秒级的时间戳,查看源码,注释写的比较清楚,虽然该方法返回的是毫秒级的时间戳,但精度取决于操作系统,很多操作系统返回的精度是10毫秒。
1/** 2 * Returns the current time in milliseconds. Note that 3 * while the unit of time of the return value is a millisecond, 4 * the granularity of the value depends on the underlying 5 * operating system and may be larger. For example, many 6 * operating systems measure time in units of tens of 7 * milliseconds. 8 * 9 * <p> See the description of the class <code>Date</code> for 10 * a discussion of slight discrepancies that may arise between 11 * "computer time" and coordinated universal time (UTC). 12 * 13 * @return the difference, measured in milliseconds, between 14 * the current time and midnight, January 1, 1970 UTC. 15 * @see java.util.Date 16 */ 17 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万次时间戳需要的时间分别是多少,这里给出在我的电脑上的测试数据:
1Benchmark Mode Cnt Score Error Units 2TimeStampTest.test1Thread avgt 0.271 s/op 3TimeStampTest.test2Thread avgt 0.272 s/op 4TimeStampTest.test4Thread avgt 0.278 s/op 5TimeStampTest.test8Thread avgt 0.375 s/op 6TimeStampTest.test16Thread avgt 0.737 s/op 7TimeStampTest.test32Thread avgt 1.474 s/op 8TimeStampTest.test64Thread avgt 2.907 s/op 9TimeStampTest.test128Thread avgt 5.732 s/op
可以看出在1-4线程下比较快,8线程之后就是线性增长了。 测试代码参考:
1@State(Scope.Benchmark) 2public class TimeStampTest { 3 4 private static final int MAX = 10000000; 5 6 public static void main(String[] args) throws RunnerException { 7 Options opt = new OptionsBuilder() 8 .include(TimeStampTest.class.getSimpleName()) 9 .forks(1) 10 .warmupIterations(1) 11 .measurementIterations(1) 12 .warmupTime(TimeValue.seconds(5)) 13 .measurementTime(TimeValue.seconds(5)) 14 .mode(Mode.AverageTime) 15 .syncIterations(false) 16 .build(); 17 18 new Runner(opt).run(); 19 } 20 21 @Benchmark 22 @Threads(1) 23 public void test1Thread() { 24 for (int i = 0; i < MAX; i++) { 25 currentTimeMillis(); 26 } 27 } 28 29 @Benchmark 30 @Threads(2) 31 public void test2Thread() { 32 for (int i = 0; i < MAX; i++) { 33 currentTimeMillis(); 34 } 35 } 36 37 @Benchmark 38 @Threads(4) 39 public void test4Thread() { 40 for (int i = 0; i < MAX; i++) { 41 currentTimeMillis(); 42 } 43 } 44 45 @Benchmark 46 @Threads(8) 47 public void test8Thread() { 48 for (int i = 0; i < MAX; i++) { 49 currentTimeMillis(); 50 } 51 } 52 53 @Benchmark 54 @Threads(16) 55 public void test16Thread() { 56 for (int i = 0; i < MAX; i++) { 57 currentTimeMillis(); 58 } 59 } 60 61 @Benchmark 62 @Threads(32) 63 public void test32Thread() { 64 for (int i = 0; i < MAX; i++) { 65 currentTimeMillis(); 66 } 67 } 68 69 @Benchmark 70 @Threads(64) 71 public void test64Thread() { 72 for (int i = 0; i < MAX; i++) { 73 currentTimeMillis(); 74 } 75 } 76 77 @Benchmark 78 @Threads(128) 79 public void test128Thread() { 80 for (int i = 0; i < MAX; i++) { 81 currentTimeMillis(); 82 } 83 } 84 85 private static long currentTimeMillis() { 86 return System.currentTimeMillis(); 87 } 88}
解法
最容易想到的方法是缓存时间戳,并使用一个独立的线程来更新它。这样获取就只是从内存中取一下,开销非常小,但缺点也很明显,更新的频率决定了时间戳的精度。
Cobar
Cobar获取和更新时间戳相关代码位于
1/** 2 * 弱精度的计时器,考虑性能不使用同步策略。 3 * 4 * @author xianmao.hexm 2011-1-18 下午06:10:55 5 */ 6public class TimeUtil { 7 private static long CURRENT_TIME = System.currentTimeMillis(); 8 9 public static final long currentTimeMillis() { 10 return CURRENT_TIME; 11 } 12 13 public static final void update() { 14 CURRENT_TIME = System.currentTimeMillis(); 15 } 16 17}
定时调度代码位于
1timer.schedule(updateTime(), 0L, TIME_UPDATE_PERIOD); 2... 3// 系统时间定时更新任务 4private TimerTask updateTime() { 5 return new TimerTask() { 6 @Override 7 public void run() { 8 TimeUtil.update(); 9 } 10 }; 11}
而Cobar中的更新间隔 TIME_UPDATE_PERIOD 是20毫秒
Sentinel
Sentinel也用到了缓存时间戳,其代码位于
1public final class TimeUtil { 2 3 private static volatile long currentTimeMillis; 4 5 static { 6 currentTimeMillis = System.currentTimeMillis(); 7 Thread daemon = new Thread(new Runnable() { 8 @Override 9 public void run() { 10 while (true) { 11 currentTimeMillis = System.currentTimeMillis(); 12 try { 13 TimeUnit.MILLISECONDS.sleep(1); 14 } catch (Throwable e) { 15 16 } 17 } 18 } 19 }); 20 daemon.setDaemon(true); 21 daemon.setName("sentinel-time-tick-thread"); 22 daemon.start(); 23 } 24 25 public static long currentTimeMillis() { 26 return currentTimeMillis; 27 } 28}
可以看到Sentinel实现的是每隔1毫秒缓存一次。 我们修改一下测试代码测试一下Sentinel的实现方式在1-128线程下的性能表现
1Benchmark Mode Cnt Score Error Units 2TimeStampTest.test1Thread avgt ≈ 10⁻⁴ s/op 3TimeStampTest.test2Thread avgt ≈ 10⁻⁴ s/op 4TimeStampTest.test4Thread avgt ≈ 10⁻⁴ s/op 5TimeStampTest.test8Thread avgt ≈ 10⁻³ s/op 6TimeStampTest.test16Thread avgt 0.001 s/op 7TimeStampTest.test32Thread avgt 0.001 s/op 8TimeStampTest.test64Thread avgt 0.003 s/op 9TimeStampTest.test128Thread avgt 0.006 s/op
可以和直接使用System.currentTimeMillis对比,差距非常明显。
最后
虽然缓存时间戳性能能提升很多,但这也仅限于非常高的并发系统中,一般比较适用于高并发的中间件,如果一般的系统来做这个优化,效果并不明显。性能优化还是要抓住主要矛盾,解决瓶颈,切忌不可过度优化。
欢迎关注我的公众号
“捉虫大师”

