相关疑难解决方法(0)

为什么在函数参数中将`const ull`更改为`const ull&`会导致性能提升?

所以,用下面的代码,改变参数的类型xconst ullconst ull&(有typedef unsigned long long ull)在约25%的加速效果,当用gcc 4.7.2和标志编译-O3 -std=c++11 -g,我想不通为什么会做出如此大的差异.

static void inline single_mult(const std::vector<ull>::iterator& data,
                  const std::vector<ull>::const_iterator& rbegin,
                  const std::vector<ull>::const_iterator& rend,
                  const ull x) {
        ull tmp=0, carry=0, i=0;
        for (auto rhs_it = rbegin; rhs_it != rend; ++rhs_it) {
                tmp = x*(*rhs_it) + data[i] + carry;
                if (tmp >= imax) {
                        carry = tmp >> numbits;
                        tmp &= imax - 1;
                } else { 
                        carry = 0;
                }
                data[i++] …
Run Code Online (Sandbox Code Playgroud)

c++ optimization performance gcc c++11

27
推荐指数
1
解决办法
1401
查看次数

在C++ 11中是否有一个模板可以推导出在将值传递给函数时使用的最佳类型?

我想写一个模板函数

template <typename T>
void f( T v );
Run Code Online (Sandbox Code Playgroud)

v如果它足够小,将通过值传递,否则通过引用到const传递.为此,我使用了一个小帮手

template <typename T, bool>
struct parameter_helper;

template <typename T>
struct parameter_helper<T, true> {
    typedef T type;
};

template <typename T>
struct parameter_helper<T, false> {
    typedef const T& type;
};

template <typename T>
struct parameter {
    typedef typename parameter_helper<T, sizeof(T) <= sizeof(void*)>::type type;
};
Run Code Online (Sandbox Code Playgroud)

在过去,我可以拥有

template <typename T>
void f( typename parameter<T>::type v );
Run Code Online (Sandbox Code Playgroud)

现在,在C++ 11中:这种辅助模板是否仍然有意义,还是有更好的方法来实现相同的效果?可能已经有现成的模板吗?我检查过<type_traits>但无法发现任何看似相关的东西.

c++ c++11

16
推荐指数
2
解决办法
649
查看次数

通过值与引用传递std算法迭代器参数

我想知道为什么在STL中的许多模板算法中,参数不是通过引用传递的,而是通过值传递的.以下是<iterator>标题中的示例:

template<class InputIterator>
typename iterator_traits<InputIterator>::difference_type
distance (InputIterator first, InputIterator last);
Run Code Online (Sandbox Code Playgroud)

当我将两个迭代器传递给此函数时,它们将被复制.我天真的想法是,最好通过const-reference传递这些迭代器,以避免复制迭代器对象:

template<class InputIterator>
typename iterator_traits<InputIterator>::difference_type
distance (const InputIterator &first, const InputIterator &last);
Run Code Online (Sandbox Code Playgroud)

可以说迭代器通常是非常小的对象,复制它们并不昂贵.但即便如此:便宜的复制将比没有复制更昂贵.

那么在STL版本中,迭代器是按值传递的原因是什么?

谢谢!

c++ templates stl

14
推荐指数
3
解决办法
6400
查看次数

标签 统计

c++ ×3

c++11 ×2

gcc ×1

optimization ×1

performance ×1

stl ×1

templates ×1