System.out.println()的消耗时间; Java语句? [英] Consumed Time of System.out.println(); Java statement?
问题描述
我听说System.out.println();
Java语句代价高昂(它消耗大量时间)
因此,我尝试评估其成本:
当我评估5条语句时... The cost = 1.0
所以我期望1条语句的成本= 0.2
但是实际上我发现了The cost = 0.0
!
I hear that the System.out.println();
Java statement is costly (it consumes a lot of time)
So I try to evaluate its cost:
When I evaluate 5 statements... The cost = 1.0
So I expect the cost of 1 statement = 0.2
But actually I found The cost = 0.0
!!
double t1 = 0;
double t2 = 0;
t1 = System.currentTimeMillis();
System.out.println("aa");
System.out.println("aa");
System.out.println("aa");
System.out.println("aa");
System.out.println("aa");
t2 = System.currentTimeMillis();
System.out.println("The cost = " + (t2-t1) );
// The cost = 1.0
t1 = System.currentTimeMillis();
System.out.println("aa");
t2 = System.currentTimeMillis();
System.out.println("The cost = " + (t2-t1) );
// The cost = 0.0
// Expected : 1.0/5 = 0.2 -- But Actual : 0.0
为什么?
推荐答案
System#currentTimeMillis
returns long
and not double
. Thus you're loosing .2
.
测试5条语句不是一个好主意,特别是当您几乎感觉不到执行它所需的时间时.我建议您测试5条以上的语句,然后将其减少到1条以上.
Testing 5 statements is not a good idea, specially when you almost don't feel the time it takes to perform it. I advise you to have more than 5 statements to test and then reduce the amount to something more than 1 as well.
You want to do a precise measurements time, it's better to use System#nanoTime
, since it gives time in nano seconds:
long startTime = System.nanoTime();
// ... the code being measured ...
long estimatedTime = System.nanoTime() - startTime;
查找"nanoTime vs currentTimeMillis",您将获得数百篇文章.
Look for "nanoTime vs currentTimeMillis" and you'll get hundreds of articles.
这篇关于System.out.println()的消耗时间; Java语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!