CKTIS / Java
Leistung und Messung in Java
Leistung und Messung in Java: Java-Leistung hängt zuerst von Algorithmuskomplexität und Datenstrukturen ab, danach von Allokation, Lokalität, Synchronisation, GC und JIT-Optimierung.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
performanceJava-Leistung hängt zuerst von Algorithmuskomplexität und Datenstrukturen ab, danach von Allokation, Lokalität, Synchronisation, GC und JIT-Optimierung.
Profile zuerst eine repräsentative Last, wähle Collections nach dominanten Operationen und miss Dauer als Differenz von System.nanoTime statt mit der Wanduhr.
Eine einzelne kalte Messung wird durch JIT-Kompilierung, Dead-code elimination und GC verzerrt; ein handgeschriebener Mikrobenchmark kann unproduktiven Code messen.
Der Ursprung von nanoTime ist beliebig und nur Differenzen zählen; Parallelität kann kleine Aufgaben bremsen und bessere Asymptotik gewinnt erst ab passender Eingabegröße.
Für Ziel 31 ergeben die Zähler linear=32 gegenüber binary=6; elapsed-nonnegative=true zeigt eine System.nanoTime-Differenz ohne maschinenabhängige Zeitangabe.
Beispiele
public class Main {
static int linearComparisons(int[] values, int target) {
int comparisons = 0;
for (int value : values) {
comparisons++;
if (value == target) break;
}
return comparisons;
}
static int binaryComparisons(int[] values, int target) {
int low = 0, high = values.length - 1, comparisons = 0;
while (low <= high) {
int middle = (low + high) >>> 1;
comparisons++;
if (values[middle] == target) break;
if (values[middle] < target) low = middle + 1;
else high = middle - 1;
}
return comparisons;
}
public static void main(String[] args) {
int[] values = new int[32];
for (int i = 0; i < values.length; i++) values[i] = i;
System.out.println("linear=" + linearComparisons(values, 31));
System.out.println("binary=" + binaryComparisons(values, 31));
long started = System.nanoTime();
long elapsed = System.nanoTime() - started;
System.out.println("elapsed-nonnegative=" + (elapsed >= 0));
}
}
Ergebnis
linear=32 binary=6 elapsed-nonnegative=true
Für Ziel 31 ergeben die Zähler linear=32 gegenüber binary=6; elapsed-nonnegative=true zeigt eine System.nanoTime-Differenz ohne maschinenabhängige Zeitangabe.