shuisheng posted:

Dear all,

Assume I have two big arrays A and B. And I want to element-wise divide

A by B. When an element of B is zero, the results are also zero.

Such as A = { 2, 4, 0, 6}

B = { 1, 0, 0, 2}

-----------------------------------------

R = { 2, 0, 0, 3}

Any fast way to avoid the slow 'if' operation.

The fastest code I can think of at the moment is the following (but

ofcourse, it tests a conditional):

#include <cstddef>

#include <cassert>

void Divide(int *pA, int const *pB, std::size_t const len)

{

assert(pA); assert(pB); assert(len);

int register temp;

int const *const poverA = pA + len;

do (temp = *pB++) ? (*pA++ /= temp) : (*pA++ = 0);

while(poverA!=pA);

}

Or maybe if you're working with a machine which has a single instruction

which takes a pointer plus an offset:

void Divide(int *const pA, int const *const pB, std::size_t const len)

{

assert(pA); assert(pB); assert(len);

int register temp;

std::size_t register i = 0;

do (temp = pB[i]) ? (pA[i] /= temp) : (pA[i] = 0);

while(++i!= len);

}

--

Frederick Gotham