不敢相信?System.currentTimeMillis() 存在性能問題
閱讀本文大概需要 3 分鐘。
來自:jianshu.com/p/d2039190b1cb
public?class?CurrentTimeMillisPerfDemo?{
????private?static?final?int?COUNT?=?100;
????public?static?void?main(String[]?args)?throws?Exception?{
????????long?beginTime?=?System.nanoTime();
????????for?(int?i?=?0;?i?????????????System.currentTimeMillis();
????????}
????????long?elapsedTime?=?System.nanoTime()?-?beginTime;
????????System.out.println("100?System.currentTimeMillis()?serial?calls:?"?+?elapsedTime?+?"?ns");
????????CountDownLatch?startLatch?=?new?CountDownLatch(1);
????????CountDownLatch?endLatch?=?new?CountDownLatch(COUNT);
????????for?(int?i?=?0;?i?????????????new?Thread(()?->?{
????????????????try?{
????????????????????startLatch.await();
????????????????????System.currentTimeMillis();
????????????????}?catch?(InterruptedException?e)?{
????????????????????e.printStackTrace();
????????????????}?finally?{
????????????????????endLatch.countDown();
????????????????}
????????????}).start();
????????}
????????beginTime?=?System.nanoTime();
????????startLatch.countDown();
????????endLatch.await();
????????elapsedTime?=?System.nanoTime()?-?beginTime;
????????System.out.println("100?System.currentTimeMillis()?parallel?calls:?"?+?elapsedTime?+?"?ns");
????}
}

jlong?os::javaTimeMillis()?{
??timeval?time;
??int?status?=?gettimeofday(&time,?NULL);
??assert(status?!=?-1,?"linux?error");
??return?jlong(time.tv_sec)?*?1000??+??jlong(time.tv_usec?/?1000);
}
調(diào)用gettimeofday()需要從用戶態(tài)切換到內(nèi)核態(tài); gettimeofday()的表現(xiàn)受Linux系統(tǒng)的計時器(時鐘源)影響,在HPET計時器下性能尤其差; 系統(tǒng)只有一個全局時鐘源,高并發(fā)或頻繁訪問會造成嚴(yán)重的爭用。
~?cat?/sys/devices/system/clocksource/clocksource0/available_clocksource
tsc?hpet?acpi_pm
~?cat?/sys/devices/system/clocksource/clocksource0/current_clocksource
tsc
~?echo?'hpet'?>?/sys/devices/system/clocksource/clocksource0/current_clocksource
public?class?CurrentTimeMillisClock?{
????private?volatile?long?now;
????private?CurrentTimeMillisClock()?{
????????this.now?=?System.currentTimeMillis();
????????scheduleTick();
????}
????private?void?scheduleTick()?{
????????new?ScheduledThreadPoolExecutor(1,?runnable?->?{
????????????Thread?thread?=?new?Thread(runnable,?"current-time-millis");
????????????thread.setDaemon(true);
????????????return?thread;
????????}).scheduleAtFixedRate(()?->?{
????????????now?=?System.currentTimeMillis();
????????},?1,?1,?TimeUnit.MILLISECONDS);
????}
????public?long?now()?{
????????return?now;
????}
????public?static?CurrentTimeMillisClock?getInstance()?{
????????return?SingletonHolder.INSTANCE;
????}
????private?static?class?SingletonHolder?{
????????private?static?final?CurrentTimeMillisClock?INSTANCE?=?new?CurrentTimeMillisClock();
????}
}
CurrentTimeMillisClock.getInstance().now()就可以了。不過,在System.currentTimeMillis()的效率沒有影響程序整體的效率時,就不必忙著做優(yōu)化,這只是為極端情況準(zhǔn)備的。推薦閱讀:
SpringBoot配置Redis序列化規(guī)則,防止亂碼
微信掃描二維碼,關(guān)注我的公眾號
朕已閱?

