PyPy 17x faster than Python. Can Python be sped up?

后端 未结 2 2035
有刺的猬
有刺的猬 2021-01-12 19:36

Solving a recent Advent of Code problem, I found my default Python was ~40x slower than PyPy. I was able to get that down to about 17x with this code by limiting calls to

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-12 20:13

    You can improve small things, but pypy will (most likely) always be faster in this task.

    For both CPython and Cython:

    • Don't read in the whole file at once. You can iterate on lines as you go, which saves you (re)allocation costs. This requires you to pre-allocate the array though.
    • Maybe switch from a list to an array.

    For Cython:

    • Mark the variable types. Especially the counters as ints and the commands as an array of ints to skip most type checks.

提交回复
热议问题