{ "cells": [ { "cell_type": "markdown", "id": "b404a1ed-4939-4bac-843e-d46c3e4ec268", "metadata": {}, "source": [ "## Comparing Cython, mpypyc, and default Python speed\n", "\n", "On a simple thing:\n", "- mypyc gives a 10x speed-up\n", "- cython-3 a 40x speed-up" ] }, { "cell_type": "code", "execution_count": 1, "id": "98f1413e-e664-4c0e-9182-556d7f192319", "metadata": { "tags": [] }, "outputs": [], "source": [ "%load_ext mypyc_ipython" ] }, { "cell_type": "code", "execution_count": 2, "id": "5286f9f6-347b-4c84-870f-677f32eb935d", "metadata": { "tags": [] }, "outputs": [], "source": [ "def py_fibonacci(n: int) -> int:\n", " if n <= 1+1:\n", " return 1\n", " else:\n", " return py_fibonacci(n-1) + py_fibonacci(n-2)" ] }, { "cell_type": "code", "execution_count": 3, "id": "a0083738-2588-4923-92b3-135038c9a248", "metadata": { "tags": [] }, "outputs": [], "source": [ "%%mypyc\n", "def my_fibonacci(n: int) -> int:\n", " if n <= 2:\n", " return 1\n", " else:\n", " return my_fibonacci(n-1) + my_fibonacci(n-2)" ] }, { "cell_type": "code", "execution_count": 4, "id": "af675113-798c-46cc-9ce0-b607420fe720", "metadata": { "tags": [] }, "outputs": [], "source": [ "%load_ext cython" ] }, { "cell_type": "code", "execution_count": 5, "id": "3060e007-0887-47c2-bcf2-f304ecace0be", "metadata": { "tags": [] }, "outputs": [], "source": [ "%%cython\n", "cpdef int cy_fibonacci(int n):\n", " if n <= 2:\n", " return 1\n", " else:\n", " return cy_fibonacci(n-1) + cy_fibonacci(n-2)" ] }, { "cell_type": "code", "execution_count": 6, "id": "444c2112-8c38-4064-b7df-3609375688fa", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "101 ms ± 503 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" ] } ], "source": [ "%timeit py_fibonacci(30)" ] }, { "cell_type": "code", "execution_count": 7, "id": "1bec3d97-229d-479f-b18d-99402c4a19d2", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8.55 ms ± 248 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" ] } ], "source": [ "%timeit my_fibonacci(30)" ] }, { "cell_type": "code", "execution_count": 8, "id": "66da0aba-d10d-4204-a8dd-90100aa495d8", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2.35 ms ± 75.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" ] } ], "source": [ "%timeit cy_fibonacci(30)" ] }, { "cell_type": "code", "execution_count": null, "id": "d2aa1e9d-a74b-4e00-9ea8-9f9baa12275b", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.3" } }, "nbformat": 4, "nbformat_minor": 5 }