Teymour
Teymour

Reputation: 2079

Is it quicker to do division batch-wise or just once?

Suppose I have the numbers: 1, 2, 4, 7, 12 and 18 (randomly chosen). When computing the mean is it quicker to do:

mean=0
loop through [1, 2, 4, 7, 12, 18]
   for each item:
     increase mean by (item/total number of items)

or

mean=0
loop through [1, 2, 4, 7, 12, 18]
   for each item:
     increase mean by (item)
divide mean by 3

or does it make no difference to the speed of the algorithm? This is a purely theoretical question (ignoring the specific chosen compiler, etc.)

Upvotes: 1

Views: 15

Answers (1)

Patrick87
Patrick87

Reputation: 28312

It depends to an extent on how smart your compiler is - some will perform lots of optimizations, others not as much. The optimization level can often be configured so that you can vary the degree to which the compiler transforms code.

In the limit of optimization, a compiler could recognize your code computes a constant value and pre-compute it during compilation and put the result in the output variable. This absolutely is possible.

Another possibility is that the compiler recognizes the loop is over a fixed range and so it removes the loop and expands the summation.

In the limit of no optimization, your first snippet does 6 division operations while the second snipped does just one. Since the other numbers of operations are the same for each of the snippets, the first snippet cannot be faster and is likely slower compared to the second snippet.

It might be instructive to learn about optimization in your language's compiler or interpreter and experiment with various levels of optimization to see how the performance of each snippet changes. You'll probably need larger input samples to get useful time measurements out.

Upvotes: 1

Related Questions