så jeg tænkte at det måtte være muligt at lave en time() metode der kunne tage en anden metode som parameter.
Dette inkluderede anonyme klasser, så det gik jeg hurtigt væk fra og over til lambda.
Er der nogle der kender en bedre metode end dette til at opnå samme resultat?
Kode: Vælg alt
public class Main {
public static void main(String[] args) {
MethodExecution me = new MethodExecution();
// Execute a command in the Main class from the MethodExecution class, so we can time it.
System.out.println(me.methodExecutionTime(()-> Main.command1()));
}
public static void command1() {
int min = 1200;
int max = 2200;
try {
Thread.sleep(ThreadLocalRandom.current().nextInt(min, max +1));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("command1 output");
}
}
class MethodExecution {
public int methodExecutionTime(Runnable function) {
long startTime = System.nanoTime();
function.run();
long stoptime = System.nanoTime();
return (int) (TimeUnit.MILLISECONDS.convert((stoptime - startTime), TimeUnit.NANOSECONDS));
}
}
output
command1 output
1938