与更具可读性的方法相比,C ++中按位异或的效率 [英] Efficiency of Bitwise XOR in c++ in comparison to more readable methods
问题描述
我最近一直在为我正在从事的研究项目编写一些代码,其中效率非常重要.我一直在考虑抓取我处理的某些常规方法,而改用按位XOR.我想知道的是,如果在g ++中使用03后是否会有所不同(如果我执行此操作说几百万次)还是相同的话?
I've recently been writing some code for a research project that I'm working on, where efficiency is very important. I've been considering scraping some of the regular methods I do things in and using bitwise XORs instead. What I'm wondering is if this will make if a difference (if I'm performing this operation say several million times) or if it's the same after I use 03 in g++.
我想到了两个例子:
我有一个实例(我正在使用纯正整数),如果n为奇数,则需要将n更改为n-1;如果n为偶数,则需要将n更改为(n + 1).我认为我有几个选择:
I had an instance where (I'm working with purely positive ints) I needed to change n to n-1 if n was odd or n to (n+1) if n was even. I figured I had a few options:
if(n%2) // or (n%2==0) and flip the order
n=n-1
else
n=n+1
或
n=n+2*n%2-1; //This of course was silly, but was the only non-bitwise 1 line I could come up with
最后:
n=n^1;
所有方法显然都做同样的事情,但是我的感觉是第三个方法将是最有效的.
All of the methods clearly do the same thing, but my feeling was that the third one would be the most efficient.
下一个示例更为笼统.假设我要比较两个正整数,其中一个会比其他整数更好.或即使我执行了数百万次此操作,差异是否也不会真正引起注意:
The next example is on a more general note. Say I'm comparing two positive integers, will one of these perform better than the others. Or will the difference really not be noticeable, even if I perform this operation several million times:
if(n_1==n_2)
if(! (n_1 ^ n_2) )
if( n_1 ^ n_2) else \do work here
在所有这些实例中,编译器将执行相同的操作吗?我只是好奇是否有实例应该使用按位运算而不信任编译器为我完成工作.
Will the compiler just do the same operation in all of these instances? I'm just curious if there is an instance when I should use bitwise operations and not trust the compiler to do the work for me.
已修正:正确的问题陈述.
Fixed:In correct statement of problem.
推荐答案
检查起来很容易,只需启动您的反汇编程序即可.看看:
It's easy enough to check, just fire up your disassembler. Take a look:
f.c:
unsigned int f1(unsigned int n)
{
n ^= 1;
return n;
}
unsigned int f2(unsigned int n)
{
if (n % 2)
n=n-1;
else
n=n+1;
return n;
}
构建和拆卸:
$ cc -O3 -c f.c
$ otool -tV f.o
f.o:
(__TEXT,__text) section
_f1:
00 pushq %rbp
01 movq %rsp,%rbp
04 xorl $0x01,%edi
07 movl %edi,%eax
09 leave
0a ret
0b nopl _f1(%rax,%rax)
_f2:
10 pushq %rbp
11 movq %rsp,%rbp
14 leal 0xff(%rdi),%eax
17 leal 0x01(%rdi),%edx
1a andl $0x01,%edi
1d cmovel %edx,%eax
20 leave
21 ret
看起来 f1()
有点短,实际上这是否重要取决于某个基准测试.
It looks like f1()
is a bit shorter, whether or not that matters in reality is up to some benchmarking.
这篇关于与更具可读性的方法相比,C ++中按位异或的效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!