fill不会变成POD类型的memset

fill不会变成POD类型的memset

本文介绍了std :: fill不会变成POD类型的memset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期望std :: fill在一个连续的容器,说std :: vector,会自动编译成memset的调用。但是,当我尝试下面的代码

I am expecting a std::fill on an continuous container, say std::vector, will automatically compiled to a call of memset. However, when I tried the following code

#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;

int main()
{
    vector<double> vec(300000);

    fill(vec.begin(),vec.end(),0.0);

    memset(&vec[0],0,vec.size()*sizeof(double));
}

gcc将第一个std :: fill编译为一个简单的循环。但我认为这可以通过SSE或其他高级向量化代码来完成。请给我一个提示。

gcc compiled the first std::fill to a simple loop. But I think it could be done by SSE or other advanced vectorized code. Please give me a hint. Thanks.

推荐答案

解决您的特定示例 double 成为一个平台特定的优化,最有可能g ++决定不做这样的事情。原因当然是任何平台使用 double 的表示, 0.0 并不意味着所有零字节。注意,另外,设置为非零的任何数字是一个完全不同的游戏,因为它不只是将每个字节设置为零:有一个特定的模式,需要遵循。

Addressing your specific example of double, it would have to be a platform specific optimization and most likely g++ decided not to do such a thing. The reason is of course any platforms using a representation of double for which 0.0 does not mean all zero bytes. Note that additionally, setting to any number OTHER than zero is a whole different game as it's not just setting every byte to zero: There is a specific pattern that needs to be followed. It gets worse with negative numbers.

除非您有特定的分析信息,表示填充的时间明显长于 memset 我不会太担心它。如果它需要很长时间,你可以手动调整手动使用 memset 或尝试解决根本原因,需要重复设置为零。

Unless you have specific profiling information that the fill is taking significantly longer than memset I wouldn't be too worried about it. If it IS taking a lot longer you can either hand-tune to manually use memset or try to address the root cause, the need to set to zero repeatedly.

这篇关于std :: fill不会变成POD类型的memset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 01:51