使用JAVA对内存进行简易的测试

JAVA内存测试

使用JAVA对内存进行简易的测试一

最近换了4条8GB DDR3 1866内存,想看看内存到底有多快。虽然现在有很多现在的软件,但是从编程的角度来说,并不是理解的很深刻,所以自己写了几个简单的程序进行测试。

基本思想

测试的方法是先在内存中建立一个大数据,然后记录读取的时候,从而理解内存的速度。
主要代码包括三块
1 定义大数据
这里定义了一个长度约为10亿(2^30)的数组。
2.随机初始化这个数据
使用Random对这个数组进行初始化。
3.对这个数据求和
使用循环进行数据累加。
主要代码如下所示。

package hello;

import java.util.Random;

public class MemoryTest {
	public static void main(String[] args) {
		// data length: 1 GiB.
		int len = 1024 * 1024 * 1024;
		Random rnd = new Random(0);
		long result = 0;

		System.out.println("Declaring...");
		long t1 = System.currentTimeMillis();
		short[] its = new short[len];

		System.out.println("Randomizing...");
		long t2 = System.currentTimeMillis();
		for (int i = 0; i < len; i++)
			its[i] =(short) rnd.nextInt();

		System.out.println("Reading...");
		long t3 = System.currentTimeMillis();
		for (int i = 0; i < len; i++)
			result += its[i];
		long t4 = System.currentTimeMillis();

		System.out.println("Result: " + result);
		System.out.println("Declaration: " + (t2 - t1));
		System.out.println("Randomization: " + (t3 - t2));
		System.out.println("Reading: " + (t4 - t3));
	}
}

测试及结果

由于程序使用了1 G长的数组,当为int型的时候,需要占用4GB的内存,已经超过了默认单个java程序占用的内存空间,需要显式分配更多内存。若指定分配5G内存,则需加上 -Xmx5g -Xms5g

测试一:数据类型 int
Declaration: 1771
Randomization: 14479
Reading: 482

测试二:数据类型 short
Declaration: 955
Randomization: 14277
Reading: 430

测试三:数据类型 byte
Declaration: 449
Randomization: 14332
Reading: 408

结论

  1. 声明的时间和使用内存大小成正比
    byte 占 1字节,short 占 2 字节, int 占 4 字节。所用的时间基本是 1:2:4,与容量成正比。
  2. 内存读取性能主要取决读取次数
    在三个测试中,都是读取10亿次,用时基本都是400+ms。时间差主要取决于数据类型不同,数据长度越大,用时越长。

猜你喜欢

转载自blog.csdn.net/weixin_43145361/article/details/84257293