Pass static methods in Java

I am trying to create a class that times the average runtime of a method. I understand how to do that by running it 100 times and taking the average of it all. Example:

private long calculateAvg(){
    long totalTime = 0;

    for(int i = 0; i < ITERATIONS; i++){
        long startTime = System.nanoTime();
        testMethod();
        long endTime = System.nanoTime();

        totalTime += (endTime - startTime);  //divide by 1000000 to get milliseconds.
    }
    return (totalTime / ITERATIONS);

}

Now I can set this to work for one static method but is there a way to pass different static methods into this to calculate instead of creating one of these for each method I want to test? If not, is there a design pattern that may work here? As of now, I am creating one of these methods for every other method I want to time and it doesn’t seem efficient because I am reusing so much code.

Answer

You can accept and run a Runnable argument:

private long calculateAvg(Runnable r) {
    //...
    long startTime = System.nanoTime();
    r.run();
    long endTime = System.nanoTime();
    //...
}

And call it like this:

long avg1 = calculateAvg(() -> testMethod());
long avg2 = calculateAvg(() -> testMethod2());

You might also want to consider some tips from How do I write a correct micro-benchmark in Java?

Leave a Reply

Your email address will not be published. Required fields are marked *