Skip to content

Instantly share code, notes, and snippets.

@crusaderky
Created December 10, 2024 18:09
Show Gist options
  • Save crusaderky/213fae2a410dcba9313c47a717a20cd2 to your computer and use it in GitHub Desktop.
Save crusaderky/213fae2a410dcba9313c47a717a20cd2 to your computer and use it in GitHub Desktop.
numpy CPU cache demo
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 23,
"id": "42fdb6ce-1d7c-485f-a1d5-0d52375c4eee",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"18.703007650000018\n",
"24.231060391000028\n",
"26.28812021700014\n",
"26.341477230000237\n"
]
}
],
"source": [
"import timeit\n",
"import numpy as np\n",
"\n",
"a = np.random.uniform(size=10**7)\n",
"b = np.random.uniform(size=10**7)\n",
"c = np.random.random(size=10**7)\n",
"d = np.random.random(size=10**7)\n",
"\n",
"def clear_cache():\n",
" c@d\n",
"\n",
"def f1():\n",
" a@b\n",
" a@b\n",
" np.log(a)\n",
" np.log(a)\n",
"\n",
"def f2():\n",
" a@b\n",
" np.log(a)\n",
" a@b\n",
" np.log(a)\n",
"\n",
"def f3():\n",
" a@b\n",
" clear_cache()\n",
" a@b\n",
" clear_cache()\n",
" np.log(a)\n",
" clear_cache()\n",
" np.log(a)\n",
" clear_cache()\n",
"\n",
"def f4():\n",
" a@b\n",
" clear_cache()\n",
" np.log(a)\n",
" clear_cache()\n",
" a@b\n",
" clear_cache()\n",
" np.log(a)\n",
" clear_cache()\n",
"\n",
"print(timeit.timeit('f1()', number=100, globals=globals()))\n",
"print(timeit.timeit('f2()', number=100, globals=globals()))\n",
"print(timeit.timeit('f3()', number=100, globals=globals()))\n",
"print(timeit.timeit('f4()', number=100, globals=globals()))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f3c94093-e4c5-4239-970d-c1c3bad8f1ff",
"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.9.19"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment