我刚刚开始使用Google基准进行微基准测试,但得到的结果我无法真正解释。我有一个函数URLify(编码空格的基本函数)。我将字符串转换为char *并将其传递给函数
这就是我使用Google基准测试和全面优化对其进行测试的方式。使用VS 2015 x64
while (state.KeepRunning()) {
char* ch = new char[str.length()*2 ]; //str is a string I want to encode
memcpy(ch, &str[0], str.length() + 1);
URLify(ch, str.length());
delete[] ch;
}
这是进行30000次迭代和5次重复的结果
BenchURLify/iterations:30000/repeats:5 5370 ns 5729 ns 30000
BenchURLify/iterations:30000/repeats:5 5366 ns 5208 ns 30000
BenchURLify/iterations:30000/repeats:5 5349 ns 5208 ns 30000
BenchURLify/iterations:30000/repeats:5 5364 ns 5729 ns 30000
BenchURLify/iterations:30000/repeats:5 5356 ns 5208 ns 30000
BenchURLify/iterations:30000/repeats:5_mean 5361 ns 5417 ns 5
BenchURLify/iterations:30000/repeats:5_median 5364 ns 5208 ns 5
BenchURLify/iterations:30000/repeats:5_stddev 8.48 ns 285 ns 5
但是,当我从代码google基准中删除delete []时,显示的结果不同,而不是我期望的结果。我以为每次迭代释放内存都比泄漏内存要慢。但这是没有delete [] ch
的结果BenchURLify/iterations:30000/repeats:5 7240 ns 7292 ns 30000
BenchURLify/iterations:30000/repeats:5 7245 ns 7292 ns 30000
BenchURLify/iterations:30000/repeats:5 7116 ns 7292 ns 30000
BenchURLify/iterations:30000/repeats:5 7091 ns 7292 ns 30000
BenchURLify/iterations:30000/repeats:5 7116 ns 6771 ns 30000
BenchURLify/iterations:30000/repeats:5_mean 7162 ns 7188 ns 5
BenchURLify/iterations:30000/repeats:5_median 7116 ns 7292 ns 5
BenchURLify/iterations:30000/repeats:5_stddev 74.6 ns 233 ns 5
所以我的问题是,为什么执行delete []比泄漏内存表现出更好的性能?或者我在这里想念什么
答案 0 :(得分:2)
有很多可能性。
答案 1 :(得分:2)
delete []函数的作用很小,并且将非常快。系统可能会在每次迭代中继续返回相同的内存,并且都可以在用户空间中完成(what happens in the kernel during malloc?有很多详细信息)。
内存按块分配给您的进程。如果让内存泄漏,则有时需要使用内核调用来扩展内存空间。这些内核调用可能比delete调用昂贵得多。