memset() 比 C 中的 for 循环更有效吗? [英] Is memset() more efficient than for loop in C?

查看:123
本文介绍了memset() 比 C 中的 for 循环更有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

memset() 是否比 for 循环更有效.

Is memset() more efficient than for loop.

考虑这个代码:

char x[500];
memset(x,0,sizeof(x));

还有这个:

char x[500];
for(int i = 0 ; i < 500 ; i ++) x[i] = 0;

哪个更有效,为什么?硬件有没有什么特殊的指令来做块级初始化.

Which one is more efficient and why? Is there any special instruction in hardware to do block level initialization.

推荐答案

当然,memset 会比那个循环快得多.请注意您如何一次处理一个字符,但这些函数经过优化,可以一次设置多个字节,甚至在可用时使用 MMX 和 SSE 指令.

Most certainly, memset will be much faster than that loop. Note how you treat one character at a time, but those functions are so optimized that set several bytes at a time, even using, when available, MMX and SSE instructions.

我认为这些优化的典型例子,通常不被注意,是 GNU C 库 strlen 函数.有人会认为它至少具有 O(n) 性能,但实际上它具有 O(n/4) 或 O(n/8) 取决于架构(是的,我知道,在大 O() 中是相同的,但您实际上获得了 八分之一 的时间).如何?棘手,但很好:strlen.

I think the paradigmatic example of these optimizations, that go unnoticed usually, is the GNU C library strlen function. One would think that it has at least O(n) performance, but it actually has O(n/4) or O(n/8) depending on the architecture (yes, I know, in big O() will be the same, but you actually get an eighth of the time). How? Tricky, but nicely: strlen.

这篇关于memset() 比 C 中的 for 循环更有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆