[英]Is it possible to get both the modulus and quotient of division in a single operation in C++?
I hear that when the processor does / or %, it will perform the same operation but one way it returns the quotient, the other way the remainder.我听说当处理器执行 / 或 % 时,它将执行相同的操作,但一种方式返回商,另一种方式返回余数。
Is it possible to get both in a single operation?是否可以在一次操作中同时获得两者? Maybe if I throw in a snippet of assembly code (which I've never done)?
也许如果我加入一段汇编代码(我从未做过)?
Yes, the compiler will do it for you.是的,编译器会为你做这件事。 Just use a divide followed by a remainder with the same operands.
只需使用除法后跟具有相同操作数的余数。
https://godbolt.org/z/oK4f4s https://godbolt.org/z/oK4f4s
void div(int n, int d, int *q, int *r)
{
*q = n / d;
*r = n % d;
}
div(int, int, int*, int*):
mov eax, edi
mov r8, rdx
cdq
idiv esi
mov DWORD PTR [r8], eax
mov DWORD PTR [rcx], edx
ret
Is it possible to get both in a single operation?
是否可以在一次操作中同时获得两者?
No, there is no such operator in C++.不,C++ 中没有这样的运算符。 There is function in the standard library which does both operations:
std::div
标准库中有一个函数可以执行这两种操作:
std::div
But this doesn't matter.但这没关系。 Whether you have one or two operations in C++ doesn't mean that the cpu would have to perform that many operations.
无论您在 C++ 中有一个还是两个操作,并不意味着 cpu 必须执行那么多操作。 A half decent optimiser will be able to translate both operations into a single instruction (assuming that is possible with the target CPU).
一个不错的优化器将能够将两个操作转换为一条指令(假设目标 CPU 可以实现)。
Yes.是的。 That's what the functions
std::remquo
and std::div
do.这就是
std::remquo
和std::div
函数所做的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.