简体   繁体   English

对处理器执行除法和模的最佳方法是什么?

[英]What is the best way to perform a division and a modulo for the processor?

How to perform a division AND a modulo at the same time. 如何同时执行除法取模。 Is it possible for the processor ? 处理器可能吗?

Like : 喜欢 :

int a, b = 8 / 3; //a = 2, b = 2

Or is there an operation which is better than : 还是有比以下更好的操作:

int a = 8 / 3;
int b = 8 % 3;

Maybe this is better ? 也许这更好?

int a = 8 / 3;
int b = 8 - a * 3;

Thanks. 谢谢。

Consider the following function: 考虑以下功能:

std::pair<int, int> divmod(int x, int y)
{
    return { x / y, x % y };
}

Compiling this with g++ -std=c++11 -O1 -S spits out the following assembly code: 使用g++ -std=c++11 -O1 -S编译会产生以下汇编代码:

movl    %edi, %eax
cltd
idivl   %esi
salq    $32, %rdx
movl    %eax, %eax
orq     %rdx, %rax
ret

As you can see, it only contains a single division on line 3. Optimizers are very good at this stuff. 如您所见,它仅在第3行包含一个除法。优化器在这方面非常擅长。

Maybe this is better? 也许这更好?

Why would it be? 为什么会这样呢? It's obscure, both to the programmer and the compiler/optimiser. 对于程序员和编译器/优化器来说都是晦涩的。 Without having looked at the compiler output, I'd imagine that any decent optimiser sees your first code and says “ah, a div and a mod being performed, I'd better emit the divmod 1 opcode”. 在没有查看编译器输出的情况下,我可以想象任何体面的优化器都能看到您的第一个代码,并说:“啊,正在执行div和mod,我最好发出divmod 1操作码”。 Whereas in the second case the optimiser is well within its right to shrug and leave it at that. 而在第二种情况下,优化器完全可以耸耸肩并留在那儿。

As a general rule (with many exceptions though), the cleanest code which has its semantics stated directly is also the code that is easiest to optimise. 作为一般规则(尽管有很多例外),直接说明其语义的最干净的代码也是最容易优化的代码。


1 For a given processor, the opcode name may differ. 1对于给定的处理器,操作码名称可能有所不同。

Perhaps you are creating a solution to a problem that <cstdlib> 's std::div is provided to solve? 也许您正在为提供<cstdlib>std::div解决的问题创建解决方案?

namespace std
{

struct div_t
{
    int quot;
    int rem;
};
struct ldiv_t
{
    long int quot;
    long int rem;
};
struct lldiv_t
{
    long long int quot;
    long long int rem;
};

  div_t div ( int numer, int denom );
 ldiv_t div ( long int numer, long int denom );
lldiv_t div ( long long int numer, long long int denom );

}; // namespace std

http://www.cplusplus.com/reference/cstdlib/div/ http://www.cplusplus.com/reference/cstdlib/div/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM