代码之家  ›  专栏  ›  技术社区  ›  Antoniossss

使用TimeUnit之间是否存在性能差异。秒和时间单位。通过Scheduled Executioners服务进行日程安排时是否会感到困惑?

  •  -2
  • Antoniossss  · 技术社区  · 6 月前

    使用ScheduledExecutionService时,用毫秒而不是秒来调度任务是否会对性能产生影响?

    例如

    ScheduledExecutorService executorService=Executors.newScheduledThreadPool(2);
    
    executorService.schedule(new MyTask(),5000,TimeUnit.MILLISECONDS);
    executorService.schedule(new MyTask(),5,TimeUnit.SECONDS); 
    

    我的问题是,使用毫秒变体会对性能产生某种影响吗?实际情况下,调度确实需要几秒钟(十分之一),但我想使用毫秒,因为单元测试可以将其设置为例如100毫秒。

    1 回复  |  直到 6 月前
        1
  •  0
  •   ipodtouch0218    6 月前

    ScheduledThreadPoolExecutor 电话 TimeUnit.toNanos :

    public ScheduledFuture<?> schedule(Runnable command,
                                       long delay,
                                       TimeUnit unit) {
        if (command == null || unit == null)
            throw new NullPointerException();
        RunnableScheduledFuture<?> t = decorateTask(command,
            new ScheduledFutureTask<Void>(command, null,
                                          triggerTime(delay, unit)));
        delayedExecute(t);
        return t;
    }
    
    private long triggerTime(long delay, TimeUnit unit) {
        return triggerTime(unit.toNanos((delay < 0) ? 0 : delay));
    }
    

    对于秒/毫秒,执行完全相同的操作,只是使用不同的常数:

    • 秒->纳米: { return x(d, C3/C0, MAX/(C3/C0)); }
    • 毫秒->纳米: { return x(d, C2/C0, MAX/(C2/C0)); }

    因此,即使在字节码级别,也很可能没有性能差异。