I want to be able to write a unit test, in a suite of performance tests that is distinct from the fast functional tests that simulates the issue and fails, correct the issue such that the test passes. For example when execution time constraint is 20 Milliseconds, the test must fail if it takes more than 20ms otherwise passes. And what if I want to put a memory consumption constraint and if consumption is more than constraint, test must fail. Is it possible that I can write a test with memory consumption constraint?
2 Answers
The total used / free memory of an program can be obtained in the program via java.lang.Runtime.getRuntime()
.
The runtime has several method which relates to the memory.
The following coding example demonstrate its usage.
package test;
import java.util.ArrayList;
import java.util.List;
public class PerformanceTest {
private static final long MEGABYTE = 1024L * 1024L;
public static long bytesToMegabytes(long bytes) {
return bytes / MEGABYTE;
}
public static void main(String[] args) {
// I assume you will know how to create a object Person yourself...
List<Person> list = new ArrayList<Person>();
for (int i = 0; i <= 100000; i++) {
list.add(new Person("Jim", "Knopf"));
}
// Get the Java runtime
Runtime runtime = Runtime.getRuntime();
// Run the garbage collector
runtime.gc();
// Calculate the used memory
long memory = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Used memory is bytes: " + memory);
System.out.println("Used memory is megabytes: "
+ bytesToMegabytes(memory));
}
}
Use System.currentTimeMillis()
to get the start time and the end time and calculate the difference.
class TimeTest1 {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long total = 0;
for (int i = 0; i < 10000000; i++) {
total += i;
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println(elapsedTime);
}
}

- 17,519
- 42
- 144
- 217
For the timing constraint you can use @org.junit.rules.Timeout
(although it's probably not what the rule is meant for) or write your own variation thereof. For the memory constraint you can write a org.junit.rules.TestRule
that compares memory usage before and after the test. Two ways to measure memory usage are the java.lang.Runtime
class and JMX.
As performance depends on many factors (load of the CI server, how much code has been jitted, etc.), it remains to be seen if the results will be conclusive/stable enough. It may be a good idea to run the tests many times and compare averages.

- 121,412
- 21
- 324
- 259
-
1thanks. I am using JUnit 4.8.2. and it does not contain TestRule. – Muhammad Ijaz Feb 18 '13 at 15:51
-
1In 4.8.2 you can use `MethodRule`. – Peter Niederwieser Feb 18 '13 at 16:57
-
1Thanks, I have implemented the MethodRule and used java.lang.Runtime to calculate the used memory. Although it is not accurate, but it gives me the rough estimates of the usage of memory. – Muhammad Ijaz Feb 19 '13 at 12:52