I have a Timer
class that measures a method execution time:
public class Timer {
private long startTime;
public long start() {
startTime=System.currentTimeMillis();
return startTime;
}
public long getElapsedTime() {
return System.currentTimeMillis()-startTime;
}
}
And I have a method that does some memory-heavy operations (like, copies into array millions of references to new different objects/millions of references to an existing object).
public static void Test {
private static Timer timer=new Timer();
private static String s0="STRING";
private static long size=5000_000L;
public static void main(String[] args) {
System.gc();
foo();
//bar(); //executed if foo() is commented
}
public static void foo() {
System.out.println("Foo starts: ");
timer.start();
for (int i=0; i<size; i++) {
arrayList.add(s0);
}
System.out.println("Foo ends: "+timer.getElapsedTime()+"ms");
}
public static void bar() {
//some code here
}
}
When foo()
is executed, a GC happens. It takes different time from run to run, for instance [Times: user=0.80 sys=0.08, real=0.39 secs]
and foo()
takes 1545 ms
. Then I have a bar()
that does a similar thing and I want to find out if it's just as efficient. It takes [Times: user=0.84 sys=0.06, real=0.31 secs]
and 1825 ms
.
What should I do to find out which method is effective, if I don't have enough RAM to avoid garbage collection during the run? Can I just subtract it like 1825-310
and 1545-390
and then compare the results?
EDIT: I run the methods separately: one is always commented out. System.gc()
is used at the very beginning.