简体   繁体   English

什么更快? System.currentTimeMillis()或Date()。getTime()?

[英]What is faster? System.currentTimeMillis() or Date().getTime()?

What is faster method? 什么是更快的方法?

System.currentTimeMillis() 

or 要么

new Date().getTime()?

Is there the faster solution to know elapsed time? 知道经过的时间有更快的解决方案吗?

If you do 如果你这样做

new Date()

it calls 它叫

/**
 * Allocates a <code>Date</code> object and initializes it so that
 * it represents the time at which it was allocated, measured to the
 * nearest millisecond.
 *
 * @see     java.lang.System#currentTimeMillis()
 */
public Date() {
    this(System.currentTimeMillis());
}

so it calls System.currentTimeMillis() AND creates an object you immediately throw away. 所以它调用System.currentTimeMillis()并创建一个立即丢弃的对象。

If you are very lucky, escape analysis will remove the redundant object and the performance will be much the same. 如果你很幸运,逃逸分析将删除冗余对象,性能将大致相同。

However, I wouldn't assume Escape Analysis will kick in and just call 但是,我不认为Escape Analysis会启动并且只是打电话

long start = System.currentTimeMillis();
// do something
long time = System.currentTimeMillis() - start;

Notes: 笔记:

  • object creation is fast, and even though it's redundant, a Date object is small and cheap to create. 对象创建很快,即使它是多余的,Date对象也很小而且很便宜。 However it contributes to a) the number of objects in your system and b) general noise in your test if you try to memory profile it. 但是它会导致a)系统中的对象数量和b)测试中的一般噪声(如果您尝试对其进行内存分析)。 To reduce variation (and speed up your code) you want to reduce memory allocations, esp redundant ones. 要减少变化(并加快代码速度),您需要减少内存分配,尤其是冗余分配。
  • this is only accurate to 1 ms and if your system corrects the time while this is running, it can be incorrect (even negative) However, it rarely does this in a dramatic fashion, and instead corrects the clock gradually meaning the time might be out by a small percentage. 这只能精确到1毫秒,如果你的系统在运行时纠正时间,它可能是不正确的(甚至是负数)但是,它很少以戏剧性的方式做到这一点,而是逐渐纠正时钟意味着时间可能会出来一小部分。 Given the variation in time due to other things happening on the system, you would be very lucky if this was you biggest problem. 鉴于由于系统上发生的其他事情导致的时间变化,如果这是您最大的问题,那么您将非常幸运。
  • System.nanoTime() could be used instead but this can have a drift of it's own. 可以使用System.nanoTime()代替,但这可能会有它自己的漂移。 Over a longer period of time eg hours, System.currentTimeMillis() can be more accurate. 在较长的时间段内,例如小时,System.currentTimeMillis()可以更准确。
  • if you are trying to write a micro-benchmark, I would ensure the code is warmed up. 如果您正在尝试编写微基准测试,我会确保代码预热。 ie ignore the first 2 - 10 seconds as there is a good chance the code isn't warm at this stage. 即忽略前2-10秒,因为在这个阶段代码很可能不温暖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM