Hi All
I execute the following snippet of code:
public static void main(String[] args)
{
while(true)
{
long startTime = System.currentTimeMillis();
byte[] bytes = new bytes[1024*1024];
System.out.println("Time taken : " + (System.currentTimeMillis()
- startTime));
}
}
After every few iterations it takes 52 ms for the allocation. Why? How
can I reduce the time taken?
Thanks
A
I tried it on my laptop, and failed to reproduce the problem. I made the
following changes:
1. Changed "new bytes" to "new byte". As noted in another article, "new
bytes" does not compile.
2. Changed "currentTimeMillis" to "nanoTime", and changed the message to
indicate time in nanoseconds.
The programs as run:
public class MemoryAllocationTest {
public static void main(String[] args) {
while (true) {
long startTime = System.nanoTime();
byte[] bytes = new byte[1024 * 1024];
System.out.println("Time taken in nanoseconds : "
+ (System.nanoTime() - startTime));
}
}
}
Here is some typical output, after leaving it to run for about 10 minutes:
Time taken in nanoseconds : 379099
Time taken in nanoseconds : 1686528
Time taken in nanoseconds : 12925106
Time taken in nanoseconds : 458158
Time taken in nanoseconds : 804851
Time taken in nanoseconds : 11001678
Time taken in nanoseconds : 476876
Time taken in nanoseconds : 698972
Time taken in nanoseconds : 11967723
Time taken in nanoseconds : 366527
Time taken in nanoseconds : 825524
Time taken in nanoseconds : 11333004
Time taken in nanoseconds : 365689
Time taken in nanoseconds : 804851
Time taken in nanoseconds : 17488536
Time taken in nanoseconds : 806527
Time taken in nanoseconds : 821892
Time taken in nanoseconds : 10484573
Time taken in nanoseconds : 431898
Time taken in nanoseconds : 866312
Time taken in nanoseconds : 12231163
Time taken in nanoseconds : 431340
Time taken in nanoseconds : 799823
I think the variation between times can be reasonably attributed to
garbage collection. Even the long times are around 12 milliseconds.
How does your output behave using nanoTime? Can you post the exact program?
Patricia