Je suis un cours d'analyse d'algorithmes et d'algorithmes. Et je veux savoir combien une simple opération +
, -
, /
, *
peut prendre sur mon ordinateur. Alors j'écris une montre simple d'arrêt comme suit:Combien de temps dure une opération simple en Java en nano secondes?
public class NanosecondsStopWatch implements StopWatch {
private PrintStream stream;
public NanosecondsStopWatch(PrintStream stream) {
this.stream = stream;
}
@Override
public void timeAndPrint(Action action) {
long start = System.nanoTime();
action.doAction();
long end = System.nanoTime();
stream.println(end-start);
}
}
public class TestingOperationsTime {
public static void main(String[] strings) {
StopWatch watch = new NanosecondsStopWatch(System.out);
watch.timeAndPrint(new Action() {
@Override
public void doAction() {
int i= 2*2;
}
});
watch.timeAndPrint(new Action() {
@Override
public void doAction() {
int i= 2/2;
}
});
watch.timeAndPrint(new Action() {
@Override
public void doAction() {
int i= 2-2;
}
});
watch.timeAndPrint(new Action() {
@Override
public void doAction() {
int i= 2+2;
}
});
}
}
Les résultats sont comme suit
2529
454
355
335
Cependant, si je change l'ordre des opérations dire comme ceci:
public class TestingOperationsTime {
public static void main(String[] strings) {
StopWatch watch = new NanosecondsStopWatch(System.out);
watch.timeAndPrint(new Action() {
@Override
public void doAction() {
int i= 2-2;
}
});
watch.timeAndPrint(new Action() {
@Override
public void doAction() {
int i= 2*2;
}
});
watch.timeAndPrint(new Action() {
@Override
public void doAction() {
int i= 2/2;
}
});
watch.timeAndPrint(new Action() {
@Override
public void doAction() {
int i= 2+2;
}
});
}
}
Le le résultat est toujours le même presque:
2494
332
309
326
Comment pouvez-vous expliquer ce comportement?
- OS: Ubuntu 14.04
- Java: 1.7.0_65
- OpenJDK Runtime Environment (IcedTea 2.5.1) (~ 7u65-2.5.1-4ubuntu1 0.14.04.2)
- OpenJDK 64 bits VM Server (build-B04 24,65, mode mixte)
- javac 1.7.0_67
Parce qu'ils sont expressions_ _constant, '2 * 2',' 2/2', '2-2' et' 2 + 2' sont évalués au moment de la compilation . Vos horaires ne reflètent pas les temps de calcul. – rgettman
duplication possible de [Y at-il un chronomètre en Java] (http://stackoverflow.com/questions/8255738/is-there-a-stopwatch-in-java) – StackFlowed
Si vous voulez savoir combien de temps quelque chose prend, effectuez le action plusieurs fois, puis calculer une moyenne. – Malt