-3

So I was doing a binary search algorithm and wondered if the runtime on a comparison for ints x,y (e.g. x < y or x > y) was faster than checking if x == y.

  • 2
    don't think there is much of a difference (actually tested and there really is no difference (kind of, there sometimes is longer time for `==` sometimes for the `<` and `>`)), either it doesn't matter if you have to do a comparison for a specific condition, either how, the more comparisons you do the more time it takes – Matiiss Aug 28 '21 at 14:10
  • 3
    here is a simple line you can run to get the total time for each of those comparisons for a million runs (run the whole thing multiple times to get more accurate results): `import timeit; print(timeit.timeit(lambda x=70: x == 70, number=1_000_000)); print(timeit.timeit(lambda x=70: x > 70, number=1_000_000)); print(timeit.timeit(lambda x=70: x < 70, number=1_000_000))` as you will notice then `==` is somewhat slower, tho the time difference is extremely small. Also as I have read then _if you worry about performance in python. don't use python_ or sth like that – Matiiss Aug 28 '21 at 14:14
  • 1
    Does this answer your question? [How can I time a code segment for testing performance with Pythons timeit?](https://stackoverflow.com/questions/2866380/how-can-i-time-a-code-segment-for-testing-performance-with-pythons-timeit) – Tomerikoo Aug 30 '21 at 09:58

1 Answers1

0

Let's build on @matiiss excellent recommendation to timeit if we want to know more. I'm going to slightly alter their timeit code so that we can look more closely at just the three compares. This will take the overhead of the function call out of the picture and hopefully highlight any differences.

import timeit
print(timeit.timeit("x == 70", setup="x = 70", number=100_000_000))
print(timeit.timeit("x > 70", setup="x = 70", number=100_000_000))
print(timeit.timeit("x < 70", setup="x = 70", number=100_000_000))

On my laptop with vanilla python, an example run (each compare tested 100 million times) returns:

2.378
2.384
2.374

(truncated to 3 places for readability)

suggesting to me that there is basically no difference. At least with this setup. Other python implementation might behave differently though.

JonSG
  • 10,542
  • 2
  • 25
  • 36
  • 1
    Might as well truncate the `000000005`, which is an artifact of printing binary numbers in decimal, and is somewhat distracting. – Stef Aug 28 '21 at 17:18
  • Sure thing. I was just pasting exactly what I was getting as a result but I agree it is a distraction – JonSG Aug 28 '21 at 17:19