Which one takes less cpu clock cycles to execute? Pythagoras formula or 16 comparisons among ints in "if" clause?

58 views Asked by At

Aprox answer is sufficient. I am suppose to check if 2 rectangles of same size overlap or not 1) Existing code checks if all (x,y) of one rectangle is withing the all (x,y) of another. So making 16 comparisons in total 2) My improvement - Calculating distance between upperl-left corner's of each rectangle and checking if this distance is smaller than diagonal of the rectangle.

Also any book/material that discusses about number of CPU clock cycles/time each operation in coding takes to execute once on CPU is appreciated.

1

There are 1 answers

0
Sudix On BEST ANSWER

This mostly depends on your approximation of the square root. A regular approximation will definitely be slower, simply because of the accuracy (and therefore, the iterations) it provides.

Given that your rectangles seem to be pretty small, the fastest algorithm would be a simple lookup: Save all possible square roots in a dictionary, and make a lookup.

If that's not what you need, you can search for another algorithm (look for approximations of square roots, or at build-in algorithms to yield square roots). Then it's up to you to calculate the necessary iterations and therefore the complexity.

Here's a link to a similar question, with some empirical approximations:

https://gamedev.stackexchange.com/questions/27196/which-opcodes-are-faster-at-the-cpu-level