整数类型的std :: swap有多快? [英] How fast is std::swap for integer types?

查看:817
本文介绍了整数类型的std :: swap有多快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

STL实现了一个通用的 std :: swap 函数来交换2个值。它可以以下列方式呈现:

 模板< class T> void swap(T& a,T& b)
{
T c(std :: move(a));
a = std :: move(b);
b = std :: move(c);但是,有一个XOR交换算法来交换2个整数( =http://en.wikipedia.org/wiki/XOR_swap_algorithm> http://en.wikipedia.org/wiki/XOR_swap_algorithm ):

  void swap_u(size_t& x,size_t& y)
{
x = x ^ y;
y = x ^ y;
x = x ^ y;
}

我的问题:
$ b


  1. 现在是优化( x86 arm

  2. C ++标准是否支持这种优化?

  3. c> std :: swap 整数的专业化?


解决方案

在大多数情况下,XOR交换不是优化。



查看此


在大多数实际情况下,使用临时寄存器的简单交换算法更高效。在其中XOR交换可能实际的有限情况包括:




  • 在指令集编码允许XOR交换被编码在较小的字节数;

  • 在寄存器压力较高的区域,它可以允许寄存器分配器避免溢出寄存器。

  • 在微控制器中可用的RAM非常有限。



由于这些情况很少见,大多数优化编译器不会生成XOR交换代码。


另请注意,您的XOR交换的实现已损坏。你需要首先检查x和y没有别名。这个检查肯定会使XOR交换变慢。



我不知道有任何使用XOR交换的标准库实现。



请注意,无论标准库如何实现,如果XOR交换真的比正常交换快,那么优化编译器会执行窥视孔优化将其变成XOR交换。这真的是一个让编译器为你选择的情况。


STL implements a generic std::swap function to swap 2 values. It can be presented in the following way:

template <class T> void swap (T& a, T& b)
{
  T c(std::move(a));
  a=std::move(b);
  b=std::move(c);
}

However, there is a XOR swap algorithm to swap 2 integers (http://en.wikipedia.org/wiki/XOR_swap_algorithm):

void swap_u( size_t& x, size_t& y )
{
   x = x^y;
   y = x^y;
   x = x^y;
}

My questions:

  1. Is it an optimization nowadays (on x86 or arm)?
  2. Does C++ standard favor this kind of optimization?
  3. Are there any real STL implementations in the wild that have std::swap specialization for integers?

解决方案

In the vast majority of situations, XOR swap is not an optimisation.

See this wiki entry.

In most practical scenarios, the trivial swap algorithm using a temporary register is more efficient. Limited situations in which XOR swapping may be practical include:

  • On a processor where the instruction set encoding permits the XOR swap to be encoded in a smaller number of bytes;
  • In a region with high register pressure, it may allow the register allocator to avoid spilling a register.
  • In microcontrollers where available RAM is very limited.

Because these situations are rare, most optimizing compilers do not generate XOR swap code.

Also note that your implementation of XOR swap is broken. You need to first check that x and y aren't aliased. This check will definitely make XOR swap slower.

I'm not aware of any standard library implementation that uses XOR swap.

Note that, regardless of what the standard library implements, if XOR swap were really faster than normal swap then optimizing compilers would do a peephole optimization to turn it into an XOR swap. This really is a case of just letting the compiler choose for you.

这篇关于整数类型的std :: swap有多快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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