清除一个小整数数组 : memset vs. for 循环

标签 c performance benchmarking

有两种方法可以将整数/ float 组清零:

memset(array, 0, sizeof(int)*arraysize);

或:

for (int i=0; i <arraysize; ++i)
    array[i]=0;

显然,memset 对于大的arraysize 更快。然而,什么时候 memset 的开销实际上大于 for 循环的开销?例如,对于大小为 5 的数组——哪个最好?第一个、第二个,甚至可能是未滚动的版本:

array[0] = 0;
array[1] = 0;
array[2] = 0;
array[3] = 0;
array[4] = 0;

最佳答案

很有可能,memset() 将被您的编译器内联(大多数编译器将其视为“内部”,这基本上意味着它是内联的,除非可能处于最低优化或除非明确禁用)。

例如,这里有一些release notes from GCC 4.3 :

Code generation of block move (memcpy) and block set (memset) was rewritten. GCC can now pick the best algorithm (loop, unrolled loop, instruction with rep prefix or a library call) based on the size of the block being copied and the CPU being optimized for. A new option -minline-stringops-dynamically has been added. With this option string operations of unknown size are expanded such that small blocks are copied by in-line code, while for large blocks a library call is used. This results in faster code than -minline-all-stringops when the library implementation is capable of using cache hierarchy hints. The heuristic choosing the particular algorithm can be overwritten via -mstringop-strategy. Newly also memset of values different from 0 is inlined.

编译器可能会对您提供的替代示例做类似的事情,但我敢打赌它不太可能。

而且它是 grep 的,一眼就能看出启动的意图(并不是说循环特别难以理解)。

关于清除一个小整数数组 : memset vs. for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1134103/

相关文章:

c - 这个C代码片段是什么意思?

linux - perl 脚本执行时间非常慢

C# HashSet 在每个 Add 上分配内存,即使在容量范围内

C++ 将 void* 转换为 int 错误

c - semclt 总是返回 -1

mongodb - 哪个 NoSQL ... 又是 :), 但用例不同

java - Fast MD5 Library 是不是比 Java 7 MD5 更快?

java - 2.5GHz Intel i7 上每秒的增量

c - cs50的copy.c文件实际上如何找到位图文件的正确部分?

c# - 了解内存高效 C# 编程的好网站/博客/书籍