有没有办法知道在java中执行循环需要多少秒?
例如:
for(int i=0; i < 1000000; i++) {
//Do some difficult task goes in here
}
Run Code Online (Sandbox Code Playgroud)
它不必是100%准确,但它只是想知道它可能需要多长时间.里面的算法是某种写入.txt文件的密钥生成器.我希望它甚至需要几分钟,所以对于我的第一次测试,我想计算秒数.
在非常古老的项目中修复bug我遇到了奇怪的方法,它看起来像这样:
void waiter() {
for (int i = 0; i < 20000; i++) ;
}
Run Code Online (Sandbox Code Playgroud)
它会导致暂停一段时间,还是会被JVM优化省略?
我正在阅读java性能调优并遇到了这个问题.
我们跑的时候
public class test {
public static void main(String a[]){
for(int i=0;i<1000000;i++){
for(int j=0;j<100000;j++){
Double d = new Double(1.0);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
JVisualVM显示内存消耗图表:

但是当我们运行下面的代码时,
public class test {
public static void main(String a[]){
for(int i=0;i<1000000;i++){
for(int j=0;j<100000;j++){
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
JVisualVM呈现锯齿:

为什么会这样?两种情况如何以及为什么gc触发限制都会改变?
public class Test {
public static void main(String[] args) {
int x = 150_000;
long start = System.currentTimeMillis();
for(int i = 0; i < x; i++) {
f1(i);
}
long end = System.currentTimeMillis();
System.out.println((end - start) / 1000.0);
}
private static long f1(int n) {
long x = 1;
for(int i = 0; i < n; i++) {
x = x + x;
}
return x;
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么x设置为150_000或者4_000_000甚至2_000_000_000不改变这个循环的执行时间?
import java.util.Random;
public class Test{
static int r = new Random().nextInt(2);
static int a(){
return r==1 ? 1 :0;
}
public static void test1() throws Exception {
//
System.out.println(1403187139018L);
for (int i = 0; i < 1073741824; i++) {}//*
// Thread.sleep(20000);
long d = 0;
for (int j = 0; j < 10; j++) {
long y = System.currentTimeMillis();
for (int x = 0; x < 1073741823; x++) {
d += r==0?1:0;
}
System.out.println((System.currentTimeMillis() -y));
}
}
public static void …Run Code Online (Sandbox Code Playgroud) while(或Java的任何其他循环)的主体可以是空的.这是因为null语句(仅由分号组成的语句)在Java中在语法上是有效的.现在考虑一下:
i = 100
j = 200
while(++i < --j); // no body in this loop
system.out.println(i);
system.out.println(j);
Run Code Online (Sandbox Code Playgroud)
我注意到,如果i的值小于j,则循环重复自身,当条件未能满足时,则只有下面的2个语句被提供.我是正确的还是这背后还有其他逻辑吗?