Skip to content

Instantly share code, notes, and snippets.

@mawillcockson
Created December 30, 2020 12:11
Show Gist options
  • Select an option

  • Save mawillcockson/e6001bcc114620aa5084cb61ddb9a799 to your computer and use it in GitHub Desktop.

Select an option

Save mawillcockson/e6001bcc114620aa5084cb61ddb9a799 to your computer and use it in GitHub Desktop.
Compare Manhattan distance calculations implemented in python
# https://twitter.com/IsntTrivial/status/1344185584013742086
echo "sum(map(abs, map(operator.sub, p, q)))"
python -m timeit \
-s "import operator;p=q=range(-10_000, 10_000, 1);" \
-s "def manhattan_distance(p, q): return sum(map(abs, map(operator.sub, p, q)))" \
"manhattan_distance(p, q)"
echo ""
echo "sum(abs(x - y) for x, y in zip(p, q))"
python -m timeit \
-s "p=q=range(-10_000, 10_000, 1);" \
-s "def manhattan_distance(p, q): return sum(abs(x - y) for x, y in zip(p, q))" \
"manhattan_distance(p, q)"
echo ""
echo "sum([abs(x - y) for x, y in zip(p, q)])"
python -m timeit \
-s "p=q=range(-10_000, 10_000, 1);" \
-s "def manhattan_distance(p, q): return sum([abs(x - y) for x, y in zip(p, q)])" \
"manhattan_distance(p, q)"
@mawillcockson
Copy link
Author

sum(map(abs, map(operator.sub, p, q)))
200 loops, best of 5: 1.68 msec per loop

sum(abs(x - y) for x, y in zip(p, q))
100 loops, best of 5: 2.5 msec per loop

sum([abs(x - y) for x, y in zip(p, q)])
100 loops, best of 5: 2.24 msec per loop

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment