Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a c++ function (built-in or otherwise) that gives the integer division and modular division results without repeating the operation?

You could write something like:

int i = 3;
int k = 2;
int division = i / k;
int remainder = i % k;

It seems as thought this would, on a low level, ask an ALU to perform two vision operations: one returning the quotient, and one returning the remainder. However, I believe an ALU would most likely calculate both in a single operation. If that is the case, this is not optimally efficient.

Is there a more efficient way of doing it, without asking the CPU to calculate twice? In other words, can it be done in a single operation from C++?

like image 914
Adam S Avatar asked Sep 14 '11 22:09

Adam S


2 Answers

Actually, the code you wrote won't generate any division instructions since the compiler can figure out the results at compile time. I wrote a little test program and set the compiler (VC++ 10SP1) to generate an assembly code listing.

#include <iostream>

using namespace std;

struct result {
    long quotient, remainder;
};

result divide(long num, long den) {
    result d = { num / den, num % den };
    return d;
}

int main() {
    result d = divide(3, 2);
    d = divide(10, 3);
    cout << d.quotient << " : " << d.remainder << endl;
    return 0;
}

I had to write it this way and explicitly tell the compiler to not inline any functions. Otherwise the compiler would have happily optimized away most of the code. Here is the resulting assembly code for the divide function.

; 8    : result divide(long num, long den) {

  00000 55       push    ebp
  00001 8b ec        mov     ebp, esp

; 9    :     result d = { num / den, num % den };

  00003 99       cdq
  00004 f7 7d 08     idiv    DWORD PTR _den$[ebp]

; 10   :     return d;
; 11   : }

  00007 5d       pop     ebp
  00008 c3       ret     0

It's smart enough to generate a single IDIV instruction and use the quotient and remainder generated by it. Modern C and C++ compilers have gotten really good at this sort of optimization. Unless you have a performance problem and have profiled your code to determine where the bottleneck is, don't try to second guess the compiler.

like image 195
Ferruccio Avatar answered Sep 30 '22 03:09

Ferruccio


ISO C99 has the ldiv function:

#include <stdlib.h>

ldiv_t ldiv(long numer, long denom);

The ldiv() function computes the value numer/denom (numerator/denominator).
It returns the quotient and remainder in a structure named ldiv_t that contains
two long members named quot and rem.

Whether at the FPU level that reduces to a single operation I couldn't say.

like image 35
Alnitak Avatar answered Sep 30 '22 03:09

Alnitak