【问题标题】:How to improve the performance for System.currentTimeMillis();?如何提高 System.currentTimeMillis(); 的性能?
【发布时间】:2022-09-30 11:24:59
【问题描述】:

System.currentTimeMillis(); 是 Java 中的系统方法。 如果串行调用此方法,似乎没有性能问题。 但是如果你不断地同时调用这个方法,性能问题就会显式地出现。作为依赖于 OS 时钟源的本机方法。但是如何在 Java 中提高它的性能。固定速率的刷新时间毫秒策略不可用。

示例如下:


int parallism = 32;

for(int i=0;i< parallism ;i++){
    new Thread(() -> {
        for(;;){

            // Focus here, how can i measure the logic efficiently
            long begin = System.currentTimeMillis();
            
            // Here may be the logic: 
            // Define empty block here means 0ms elapsed

            long elapsed = (System.currentTimeMillis() - begin);
            if(elapsed >= 5){
                System.err.println(\"Elapsed: \"+elapsed+\" ms.\");
            }
        }
    }).start();
}

Thread.sleep(Integer.MAX_VALUE); // Just avoid process exit


  • 实例化 32 个线程会更受欢迎。
  • 你想达到什么目的?
  • 提供的代码不是您如何衡量currentTimeMillis 实际花费的时间。没有办法让它更快。使用您在此处实际尝试执行的操作来编辑问题。为什么会出现?没有通用的“只用这个代替”的答案,但是对于特定的用例,可能会有一个特定的答案。
  • 我只想测量 Thread.run() 中定义的代码的运行时间。
  • 你得到了什么?

标签: java performance time clock


【解决方案1】:

性能低的原因:https://pzemtsov.github.io/2017/07/23/the-slow-currenttimemillis.html

(无法使用)另一种解决方案:https://programmer.group/5e85bd0cc8b52.html

等我发布我的解决方案....

【讨论】:

  • 仅链接的答案是 Stack Overflow 上的 discouraged。在您的答案中包含摘要或引用链接帖子的重要部分。
【解决方案2】:

尝试使用

System.nanoTime() is better than System.currentTimeMills();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 2021-10-13
    • 2018-03-01
    • 2020-04-28
    • 2014-09-22
    • 2010-11-04
    相关资源
    最近更新 更多