我在计算多个for
中包含的两种方法时遇到问题。我正在使用System.currentTimeMillis();
。问题是我不知道在哪里放置开始时间和结束时间。我想为methodA和methodB执行5次执行。
当我运行它时,我获得了methodA的12 ms
和方法B的0ms
,但程序运行大约需要10分钟。代码如下:
int count = 0;
double e = 0.3;
long startTimeA;
long endTimeA;
long startTimeB;
long endTimeB;
long sumA = 0;
long sumB = 0;
for(int k=0; k<5; k++){
startTimeA = System.currentTimeMillis();
startTimeB = System.currentTimeMillis();
for(int i = 0; i < 40; i++) {
for(int j = i + 1; j < 40; j++) {
double a = methodA();
endTimeA = System.currentTimeMillis() - startTimeA;
double b = methodB();
endTimeB = System.currentTimeMillis() - startTimeB;
int c = methodC();
}
sumA += endTimeA;
sumB += entTimeB;
}
}
System.out.println("total time A: " + sumA + " ms");
System.out.println("total time B: " + sumB + " ms");
答案 0 :(得分:1)
您应该阅读micro-benchmarking
以及如何在实践中这样做。
这是一种完成你想要做的事情的方法:
private void doSomething() {
long startTimeA = System.currentTimeMillis();
executeA();
long endTimeA = System.currentTimeMillis();
System.out.println("Total Time A: " + (endTimeA - startTimeA));
long startTimeB = System.currentTimeMillis();
executeB();
long endTimeB = System.currentTimeMillis() - startTimeB;
System.out.println("Total Time B: " + (endTimeB - startTimeB));
}
private void executeA() {
for(int k=0; k<5; k++) {
for(int i = 0; i < 40; i++) {
for(int j = i + 1; j < 40; j++) {
double a = methodA();
}
}
}
}
private void executeB() {
for(int k=0; k<5; k++) {
for(int i = 0; i < 40; i++) {
for(int j = i + 1; j < 40; j++) {
double b = methodB();
}
}
}
}
答案 1 :(得分:1)
for(int k=0; k<5; k++){
sumA = 0;
sumB = 0;
for(int i = 0; i < 40; i++) {
for(int j = i + 1; j < 40; j++) {
startTimeA = System.currentTimeMillis();
double a = methodA();
endTimeA = System.currentTimeMillis() - startTimeA;
sumA += endTimeA;
startTimeB = System.currentTimeMillis();
double b = methodB();
endTimeB = System.currentTimeMillis() - startTimeB;
sumB += endTimeB;
int c = methodC();
}
}
System.out.println("total time A: " + sumA + " ms");
System.out.println("total time B: " + sumB + " ms");
}
答案 2 :(得分:1)
移动
sumA += endTimeA;
sumB += entTimeB;
进入&#34;对于j&#34;循环。