我正在做一些关于插入和读取时间的性能测试,HashMap
只是为了好玩看看HashMap
与其他数据结构相比性能如何。
我有一个文本文件,其中包含100万个英语单词,其频率以这种格式显示-
hello 100
world 5000
good 2000
bad 9000
...
现在,我逐行读取该文件并将其存储在其中,HashMap
这样我就可以使用以下代码来测量插入性能。
Map<String, String> wordTest = new HashMap<String, String>();
try {
fis = new FileInputStream(FILE_LOCATION);
reader = new BufferedReader(new InputStreamReader(fis));
long startTime = System.nanoTime();
String line = reader.readLine();
while (line != null) {
// split the string on whitespace
String[] splitString = line.split("\\s+");
// now put it in HashMap as key value pair
wordTest.put(splitString[0].toLowerCase().trim(), splitString[1].trim());
line = reader.readLine();
}
long endTime = System.nanoTime() - startTime;
System.out.println("Insertion Time: " +TimeUnit.MILLISECONDS.convert(endTime, TimeUnit.NANOSECONDS));
}
现在,我也想在中测量读取性能HashMap
。我知道如何从HashMap获取值,但不确定读取时间是什么意思?这意味着从HashMap中搜索一个字符串需要花费多少时间?
从这个链接-https: //github.com/jpountz/tries/wiki/Benchmark看一眼,基本上让我感到困惑。在此链接中,他们ReadTime
不确定但意味着什么?
所以我的问题就是我的问题,如果我需要计算ReadTime
它的一般含义是什么?我是否应该对单个字符串查找花费多少时间HashMap
或其他时间进行基准测试?
或者,总的来说,如果我想从HashMap测量ReadTime,应该怎么做?
注意:我从不建议您这样做会为基准测试带来完美的结果。它只是一个示例代码,用于读写中的随机值HashMap
。
String atoz = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ0123456789";
Map<String, String> wordTest = new HashMap<String, String>();
//write logic
long startTime = System.currentTimeMillis();
for (int i = 0; i < 24223400; i++) {
int begin1 = 1 + (int) (Math.random() * ((atoz.length() - 1) + 1));
int end1 = begin1 + (int) (Math.random() * ((atoz.length() - begin1) + 1));
int begin2 = 1 + (int) (Math.random() * ((atoz.length() - 1) + 1));
int end2 = begin2 + (int) (Math.random() * ((atoz.length() - begin2) + 1));
wordTest.put(atoz.substring(begin1, end1), atoz.substring(begin2, end2));
}
long endTime = System.currentTimeMillis();
System.out.println("Time taken:" + (endTime - startTime) + " ms to insert "
+ wordTest.size() + " records.");
// Read logic
String atoz1 = "ABCDEFGHIJKLMNOPQURSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
int counter=0;
long startTime1 = System.currentTimeMillis();
for (int i = 0; i < 24223400; i++) {
int begin1 = 1 + (int) (Math.random() * ((atoz1.length() - 1) + 1));
int end1 = begin1 + (int) (Math.random() * ((atoz1.length() - begin1) + 1));
if(wordTest.get(atoz1.substring(begin1, end1))==null){
counter++;
}
}
long endTime1 = System.currentTimeMillis();
System.out.println("Time taken:" + (endTime1 - startTime1) + " ms to read " + 24223400
+ " records." + " Success hit:"+counter);
输出:
Time taken:4440 ms to insert 1953 records.
Time taken:2839 ms to read 24223400 records. Success hit:8743257
注意:所有键排列都在1953年记录之后完成,因此请尝试使用其他随机字符串和逻辑。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句