<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          低開銷獲取時間戳

          共 14951字,需瀏覽 30分鐘

           ·

          2021-04-14 12:29

          前言

          在前面文章《Cobar SQL審計的設(shè)計與實現(xiàn)》中提了一句關(guān)于時間戳獲取性能的問題

          獲取操作系統(tǒng)時間,在Java中直接調(diào)用 System.currentTimeMillis(); 就可以,但在Cobar中如果這么獲取時間,就會導致性能損耗非常嚴重(怎么解決?去Cobar的github倉庫上看看代碼吧)。

          這個話題展開具體說說,我們在Java中獲取時間戳的方法是System.currentTimeMillis(),返回的是毫秒級的時間戳,查看源碼,注釋寫的比較清楚,雖然該方法返回的是毫秒級的時間戳,但精度取決于操作系統(tǒng),很多操作系統(tǒng)返回的精度是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();

          關(guān)于為什么System.currentTimeMillis()慢,有大佬寫了文章詳細地闡述了原因,建議仔細閱讀,非常深入和詳細,文章地址

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

          總結(jié)起來原因是System.currentTimeMillis調(diào)用了gettimeofday()

          • 調(diào)用gettimeofday()需要從用戶態(tài)切換到內(nèi)核態(tài);
          • gettimeofday()的表現(xiàn)受Linux系統(tǒng)的計時器(時鐘源)影響,在HPET計時器下性能尤其差;
          • 系統(tǒng)只有一個全局時鐘源,高并發(fā)或頻繁訪問會造成嚴重的爭用。

          我們測試一下System.currentTimeMillis()在不同線程下的性能,這里使用中間件常用的JHM來測試,測試1到128線程下獲取1000萬次時間戳需要的時間分別是多少,這里給出在我的電腦上的測試數(shù)據(jù):

          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();
              }
          }

          解法

          最容易想到的方法是緩存時間戳,并使用一個獨立的線程來更新它。這樣獲取就只是從內(nèi)存中取一下,開銷非常小,但缺點也很明顯,更新的頻率決定了時間戳的精度。

          Cobar

          Cobar獲取和更新時間戳相關(guān)代碼位于

          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();
              }

          }

          定時調(diào)度代碼位于

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

          timer.schedule(updateTime(), 0L, TIME_UPDATE_PERIOD);
          ...
          // 系統(tǒng)時間定時更新任務(wù)
          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實現(xiàn)的是每隔1毫秒緩存一次。

          我們修改一下測試代碼測試一下Sentinel的實現(xiàn)方式在1-128線程下的性能表現(xiàn)

          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?3           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對比,差距非常明顯。

          最后

          雖然緩存時間戳性能能提升很多,但這也僅限于非常高的并發(fā)系統(tǒng)中,一般比較適用于高并發(fā)的中間件,如果一般的系統(tǒng)來做這個優(yōu)化,效果并不明顯。性能優(yōu)化還是要抓住主要矛盾,解決瓶頸,切忌不可過渡優(yōu)化。


          歡迎關(guān)注我的公眾號“捉蟲大師”


          瀏覽 48
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  欧美激情视频一区二区三区不卡 | 激情中文网 | 亚洲第五自拍 | 一区二区三区四区免费在线 | 超碰免费在线97 |