A place to cache linked articles (think custom and personal wayback machine)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.md 36KB

4 vuotta sitten
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. title: Speed up your Python using Rust
  2. url: https://developers.redhat.com/blog/2017/11/16/speed-python-using-rust/
  3. hash_url: 6a759885012094d09d4b2d9f8f96fbbc
  4. <h2>What is Rust?</h2>
  5. <p><strong>Rust</strong> is a systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety.</p>
  6. <p><strong>Featuring</strong></p>
  7. <ul>
  8. <li>zero-cost abstractions</li>
  9. <li>move semantics</li>
  10. <li>guaranteed memory safety</li>
  11. <li>threads without data races</li>
  12. <li>trait-based generics</li>
  13. <li>pattern matching</li>
  14. <li>type inference</li>
  15. <li>minimal runtime</li>
  16. <li>efficient C bindings</li>
  17. </ul>
  18. <p>Description is taken from <a href="http://rust-lang.org">rust-lang.org</a>.</p>
  19. <h2><a id="user-content-why-does-it-matter-for-a-python-developer" class="anchor" href="https://github.com/rochacbruno/rust-python-example#why-does-it-matter-for-a-python-developer"></a>Why does it matter for a Python developer?</h2>
  20. <p>The better description of Rust I heard from <a href="https://github.com/dlight"><strong>Elias</strong></a> (a member of the <a href="https://t.me/rustlangbr"><strong>Rust Brazil Telegram Group)</strong></a>.</p>
  21. <blockquote><p><strong>Rust is</strong> a language that allows you to build high level abstractions, but without giving up low-level control &#8211; that is, control of how data is represented in memory, control of which threading model you want to use etc.<br />
  22. <strong>Rust is</strong> a language that can usually detect, during compilation, the worst parallelism and memory management errors (such as accessing data on different threads without synchronization, or using data after they have been deallocated), but gives you a hatch escape in the case you really know what you&#8217;re doing.<br />
  23. <strong>Rust is</strong> a language that, because it has no runtime, can be used to integrate with any runtime; you can write a native extension in Rust that is called by a program node.js, or by a python program, or by a program in ruby, lua etc. and, however, you can script a program in Rust using these languages. &#8212; &#8220;Elias Gabriel Amaral da Silva&#8221;</p></blockquote>
  24. <p>There is a bunch of Rust packages out there to help you extending Python with Rust.</p>
  25. <p>I can mention <a href="https://github.com/getsentry/milksnake">Milksnake</a> created by Armin Ronacher (the creator of Flask) and also <a href="https://github.com/PyO3/pyo3">PyO3</a> The Rust bindings for Python interpreter.</p>
  26. <h3><em>See a complete reference list at the bottom of this article.</em></h3>
  27. <p>Let&#8217;s<strong> see it in action</strong></p>
  28. <p>For this post, I am going to use <a href="https://github.com/dgrunwald/rust-cpython">Rust Cpython</a>, it&#8217;s the only one I have tested, it is compatible with stable version of Rust and found it straightforward to use.</p>
  29. <blockquote><p><strong>NOTE</strong>: <a href="https://github.com/PyO3/pyo3">PyO3</a> is a fork of rust-cpython, comes with many improvements, but works only with the nightly version of Rust, so I prefered to use the stable for this post, anyway the examples here must work also with PyO3.</p></blockquote>
  30. <p><strong>Pros:</strong> It is easy to write Rust functions and import from Python and as you will see by the benchmarks it worth in terms of performance.</p>
  31. <p><strong>Cons:</strong> The distribution of your <strong>project/lib/framework</strong> will demand the Rust module to be compiled on the target system because of variation of environment and architecture, there will be a <strong>compiling</strong> stage which you don&#8217;t have when installing Pure Python libraries, you can make it easier using <a href="https://pypi.python.org/pypi/setuptools-rust">rust-setuptools</a> or using the <a href="https://github.com/getsentry/milksnake">MilkSnake</a> to embed binary data in Python Wheels.</p>
  32. <h2><a id="user-content-python-is-sometimes-slow" class="anchor" href="https://github.com/rochacbruno/rust-python-example#python-is-sometimes-slow"></a>Python is sometimes slow</h2>
  33. <p>Yes, Python is known for being &#8220;slow&#8221; in some cases and the good news is that this doesn&#8217;t really matter depending on your project goals and priorities. For most projects, this detail will not be very important.</p>
  34. <p>However, you may face the <strong>rare</strong> case where a single function or module is taking too much time and is detected as the bottleneck of your project performance, often happens with string parsing and image processing.</p>
  35. <h2><a id="user-content-example" class="anchor" href="https://github.com/rochacbruno/rust-python-example#example"></a>Example</h2>
  36. <p>Let&#8217;s say you have a Python function which does a string processing, take the following easy example of <code>counting pairs of repeated chars</code>, but have in mind that this example can be reproduced with other <code>string processing</code> functions or any other generally slow process in Python.</p>
  37. <div class="highlight highlight-source-shell">
  38. <pre><span class="pl-c"># How many subsequent-repeated group of chars are in the given string? </span>
  39. abCCdeFFghiJJklmnopqRRstuVVxyZZ... {millions of chars here}
  40. 1 2 3 4 5 6</pre>
  41. </div>
  42. <p>Python is slow for doing large <code>string</code> processing, so you can use <code>pytest-benchmark</code> to compare a <code>Pure Python (with Iterator Zipping)</code> function versus a <code>Regexp</code> implementation.</p>
  43. <div class="highlight highlight-source-shell">
  44. <pre><span class="pl-c"># Using a Python3.6 environment</span>
  45. $ pip3 install pytest pytest-benchmark
  46. </pre>
  47. </div>
  48. <p>Then write a new Python program called <code>doubles.py</code></p>
  49. <div class="highlight highlight-source-python">
  50. <pre><span class="pl-k">import</span> re
  51. <span class="pl-k">import</span> string
  52. <span class="pl-k">import</span> random
  53. <span class="pl-c"># Python ZIP version</span>
  54. <span class="pl-k">def</span> <span class="pl-en">count_doubles</span>(<span class="pl-smi">val</span>):
  55. total <span class="pl-k">=</span> <span class="pl-c1">0
  56. </span> # there is an improved version later on this post
  57. <span class="pl-k">for</span> c1, c2 <span class="pl-k">in</span> <span class="pl-c1">zip</span>(val, val[<span class="pl-c1">1</span>:]):
  58. <span class="pl-k">if</span> c1 <span class="pl-k">==</span> c2:
  59. total <span class="pl-k">+=</span> <span class="pl-c1">1</span>
  60. <span class="pl-k">return</span> total
  61. <span class="pl-c"># Python REGEXP version</span>
  62. double_re <span class="pl-k">=</span> re.compile(<span class="pl-sr"><span class="pl-k">r</span><span class="pl-pds">'</span><span class="pl-k">(?=</span>(<span class="pl-c1">.</span>)<span class="pl-ent">\1</span>)<span class="pl-pds">'</span></span>)
  63. <span class="pl-k">def</span> <span class="pl-en">count_doubles_regex</span>(<span class="pl-smi">val</span>):
  64. <span class="pl-k">return</span> <span class="pl-c1">len</span>(double_re.findall(val))
  65. <span class="pl-c"># Benchmark it</span>
  66. <span class="pl-c"># generate 1M of random letters to test it</span>
  67. val <span class="pl-k">=</span> <span class="pl-s"><span class="pl-pds">'</span><span class="pl-pds">'</span></span>.join(random.choice(string.ascii_letters) <span class="pl-k">for</span> i <span class="pl-k">in</span> <span class="pl-c1">range</span>(<span class="pl-c1">1000000</span>))
  68. <span class="pl-k">def</span> <span class="pl-en">test_pure_python</span>(<span class="pl-smi">benchmark</span>):
  69. benchmark(count_doubles, val)
  70. <span class="pl-k">def</span> <span class="pl-en">test_regex</span>(<span class="pl-smi">benchmark</span>):
  71. benchmark(count_doubles_regex, val)</pre>
  72. </div>
  73. <p>Run <strong>pytest</strong> to compare:</p>
  74. <div class="highlight highlight-source-shell">
  75. <pre>$ pytest doubles.py
  76. =============================================================================
  77. platform linux -- Python 3.6.0, pytest-3.2.3, py-1.4.34, pluggy-0.4.
  78. benchmark: 3.1.1 (defaults: timer=time.perf_counter disable_gc=False min_roun
  79. rootdir: /Projects/rustpy, inifile:
  80. plugins: benchmark-3.1.1
  81. collected 2 items
  82. doubles.py ..
  83. -----------------------------------------------------------------------------
  84. Name (time <span class="pl-k">in</span> ms) Min Max Mean
  85. -----------------------------------------------------------------------------
  86. test_regex 24.6824 (1.0) 32.3960 (1.0) 27.0167 (1.0)
  87. test_pure_python 51.4964 (2.09) 62.5680 (1.93) 52.8334 (1.96)
  88. -----------------------------------------------------------------------------
  89. </pre>
  90. </div>
  91. <p>Lets take the <code>Mean</code> for comparison:</p>
  92. <ul>
  93. <li><strong>Regexp</strong> &#8211; 27.0167 <strong>&lt;&#8211; less is better</strong></li>
  94. <li><strong>Python Zip</strong> &#8211; 52.8334</li>
  95. </ul>
  96. <h1><a id="user-content-extending-python-with-rust" class="anchor" href="https://github.com/rochacbruno/rust-python-example#extending-python-with-rust"></a>Extending Python with Rust</h1>
  97. <h2><a id="user-content-create-a-new-crate" class="anchor" href="https://github.com/rochacbruno/rust-python-example#create-a-new-crate"></a>Create a new crate</h2>
  98. <blockquote><p><strong>crate</strong> is how we call Rust Packages.</p></blockquote>
  99. <p>Having rust installed (recommended way is <a href="https://www.rustup.rs/">https://www.rustup.rs/</a>) Rust is also available on Fedora and RHEL repositories by the <a href="https://developers.redhat.com/blog/2017/11/01/getting-started-rust-toolset-rhel/">rust-toolset</a></p>
  100. <blockquote><p>I used <code>rustc 1.21.0</code></p></blockquote>
  101. <p>In the same folder run:</p>
  102. <div class="highlight highlight-source-shell">
  103. <pre>cargo new pyext-myrustlib</pre>
  104. </div>
  105. <p>It creates a new Rust project in that same folder called <code>pyext-myrustlib</code> containing the <code>Cargo.toml</code> (cargo is the Rust package manager) and also a <code>src/lib.rs</code> (where we write our library implementation).</p>
  106. <h2><a id="user-content-edit-cargotoml" class="anchor" href="https://github.com/rochacbruno/rust-python-example#edit-cargotoml"></a>Edit Cargo.toml</h2>
  107. <p>It will use the <code>rust-cpython</code> crate as dependency and tell cargo to generate a <code>dylib</code> to be imported from Python.</p>
  108. <div class="highlight highlight-source-toml">
  109. <pre>[<span class="pl-en">package</span>]
  110. <span class="pl-smi">name</span> = <span class="pl-s"><span class="pl-pds">"</span>pyext-myrustlib<span class="pl-pds">"</span></span>
  111. <span class="pl-smi">version</span> = <span class="pl-s"><span class="pl-pds">"</span>0.1.0<span class="pl-pds">"</span></span>
  112. <span class="pl-smi">authors</span> = [<span class="pl-s"><span class="pl-pds">"</span>Bruno Rocha &lt;rochacbruno@gmail.com&gt;<span class="pl-pds">"</span></span>]
  113. [<span class="pl-en">lib</span>]
  114. <span class="pl-smi">name</span> = <span class="pl-s"><span class="pl-pds">"</span>myrustlib<span class="pl-pds">"</span></span>
  115. <span class="pl-smi">crate-type</span> = [<span class="pl-s"><span class="pl-pds">"</span>dylib<span class="pl-pds">"</span></span>]
  116. [<span class="pl-en">dependencies</span>.<span class="pl-en">cpython</span>]
  117. <span class="pl-smi">version</span> = <span class="pl-s"><span class="pl-pds">"</span>0.1<span class="pl-pds">"</span></span>
  118. <span class="pl-smi">features</span> = [<span class="pl-s"><span class="pl-pds">"</span>extension-module<span class="pl-pds">"</span></span>]</pre>
  119. </div>
  120. <h2><a id="user-content-edit-srclibrs" class="anchor" href="https://github.com/rochacbruno/rust-python-example#edit-srclibrs"></a>Edit src/lib.rs</h2>
  121. <p>What we need to do:</p>
  122. <ol>
  123. <li>Import all macros from <code>cpython</code> crate.</li>
  124. <li>Take <code>Python</code> and <code>PyResult</code> types from CPython into our lib scope.</li>
  125. <li>Write the <code>count_doubles</code> function implementation in <code>Rust</code>, note that this is very similar to the Pure Python version except for:
  126. <ul>
  127. <li>It takes a <code>Python</code> as first argument, which is a reference to the Python Interpreter and allows Rust to use the <code>Python GIL</code>.</li>
  128. <li>Receives a <code>&amp;str</code> typed <code>val</code> as reference.</li>
  129. <li>Returns a <code>PyResult</code> which is a type that allows the rise of Python exceptions.</li>
  130. <li>Returns an <code>PyResult</code> object in <code>Ok(total)</code> (<strong>Result</strong> is an enum type that represents either success (Ok) or failure (Err)) and as our function is expected to return a <code>PyResult</code> the compiler will take care of <strong>wrapping</strong> our <code>Ok</code> on that type. (note that our PyResult expects a <code>u64</code> as return value).</li>
  131. </ul>
  132. </li>
  133. <li>Using <code>py_module_initializer!</code> macro we register new attributes to the lib, including the <code>__doc__</code> and also we add the <code>count_doubles</code> attribute referencing our <code>Rust implementation of the function</code>.
  134. <ul>
  135. <li>Attention to the names <strong>lib</strong>myrustlib, <strong>initlib</strong>myrustlib, and <strong>PyInit.</strong></li>
  136. <li>We also use the <code>try!</code> macro, which is the equivalent to Python&#8217;s<code>try.. except</code>.</li>
  137. <li>Return <code>Ok(())</code> &#8211; The <code>()</code> is an empty result tuple, the equivalent of <code>None</code> in Python.</li>
  138. </ul>
  139. </li>
  140. </ol>
  141. <div class="highlight highlight-source-rust">
  142. <pre>#[macro_use]
  143. <span class="pl-k">extern</span> <span class="pl-k">crate</span> cpython;
  144. <span class="pl-k">use</span> cpython<span class="pl-k">::</span>{Python, PyResult};
  145. <span class="pl-k">fn</span> <span class="pl-en">count_doubles</span>(_py: Python, val: <span class="pl-k">&amp;</span><span class="pl-k">str</span>) -&gt; PyResult&lt;<span class="pl-k">u64</span>&gt; {
  146. <span class="pl-k">let</span> <span class="pl-k">mut</span> total <span class="pl-k">=</span> <span class="pl-c1">0u64</span>;
  147. // There is an improved version later on this post
  148. <span class="pl-k">for</span> (c1, c2) <span class="pl-k">in</span> val.<span class="pl-en">chars</span>().<span class="pl-en">zip</span>(val.<span class="pl-en">chars</span>().<span class="pl-en">skip</span>(<span class="pl-c1">1</span>)) {
  149. <span class="pl-k">if</span> c1 <span class="pl-k">==</span> c2 {
  150. total <span class="pl-k">+=</span> <span class="pl-c1">1</span>;
  151. }
  152. }
  153. <span class="pl-c1">Ok</span>(total)
  154. }
  155. <span class="pl-en">py_module_initializer!</span>(libmyrustlib, initlibmyrustlib, PyInit_myrustlib, <span class="pl-k">|</span>py, m <span class="pl-k">|</span> {
  156. <span class="pl-c1">try!</span>(m.<span class="pl-en">add</span>(py, <span class="pl-s">"__doc__"</span>, <span class="pl-s">"This module is implemented in Rust"</span>));
  157. <span class="pl-c1">try!</span>(m.<span class="pl-en">add</span>(py, <span class="pl-s">"count_doubles"</span>, <span class="pl-en">py_fn!</span>(py, <span class="pl-en">count_doubles</span>(val: <span class="pl-k">&amp;</span><span class="pl-k">str</span>))));
  158. <span class="pl-c1">Ok</span>(())
  159. });
  160. </pre>
  161. </div>
  162. <h2>Now let&#8217;s build it with cargo</h2>
  163. <div class="highlight highlight-source-shell">
  164. <pre>$ cargo build --release
  165. Finished release [optimized] target(s) <span class="pl-k">in</span> 0.0 secs
  166. $ ls -la target/release/libmyrustlib<span class="pl-k">*</span>
  167. target/release/libmyrustlib.d
  168. target/release/libmyrustlib.so<span class="pl-k">*</span> <span class="pl-k">&lt;</span>-- Our dylib is here</pre>
  169. </div>
  170. <p>Now let&#8217;s copy the generated <code>.so</code> lib to the same folder where our <code>doubles.py</code> is located.</p>
  171. <blockquote><p>NOTE: on <strong>Fedora</strong> you must get a <code>.so</code> in other system you may get a <code>.dylib</code> and you can rename it changing extension to <code>.so</code>.</p></blockquote>
  172. <div class="highlight highlight-source-shell">
  173. <pre>$ <span class="pl-c1">cd</span> ..
  174. $ ls
  175. doubles.py pyext-myrustlib/
  176. $ cp pyext-myrustlib/target/release/libmyrustlib.so myrustlib.so
  177. $ ls
  178. doubles.py myrustlib.so pyext-myrustlib/</pre>
  179. </div>
  180. <blockquote><p>Having the <code>myrustlib.so</code> in the same folder or added to your Python path allows it to be directly imported, transparently as it was a Python module.</p>
  181. <p>&nbsp;</p></blockquote>
  182. <h2><a id="user-content-importing-from-python-and-comparing-the-results" class="anchor" href="https://github.com/rochacbruno/rust-python-example#importing-from-python-and-comparing-the-results"></a>Importing from Python and comparing the results</h2>
  183. <p>Edit your <code>doubles.py</code> now importing our <code>Rust implemented</code> version and adding a <code>benchmark</code> for it.</p>
  184. <div class="highlight highlight-source-python">
  185. <pre><span class="pl-k">import</span> re
  186. <span class="pl-k">import</span> string
  187. <span class="pl-k">import</span> random
  188. <span class="pl-k">import</span> myrustlib <span class="pl-c"># &lt;-- Import the Rust implemented module (myrustlib.so)</span>
  189. <span class="pl-k">def</span> <span class="pl-en">count_doubles</span>(<span class="pl-smi">val</span>):
  190. <span class="pl-s"><span class="pl-pds">"""</span>Count repeated pair of chars ins a string<span class="pl-pds">"""</span></span>
  191. total <span class="pl-k">=</span> <span class="pl-c1">0</span>
  192. <span class="pl-k">for</span> c1, c2 <span class="pl-k">in</span> <span class="pl-c1">zip</span>(val, val[<span class="pl-c1">1</span>:]):
  193. <span class="pl-k">if</span> c1 <span class="pl-k">==</span> c2:
  194. total <span class="pl-k">+=</span> <span class="pl-c1">1</span>
  195. <span class="pl-k">return</span> total
  196. double_re <span class="pl-k">=</span> re.compile(<span class="pl-sr"><span class="pl-k">r</span><span class="pl-pds">'</span><span class="pl-k">(?=</span>(<span class="pl-c1">.</span>)<span class="pl-ent">\1</span>)<span class="pl-pds">'</span></span>)
  197. <span class="pl-k">def</span> <span class="pl-en">count_doubles_regex</span>(<span class="pl-smi">val</span>):
  198. <span class="pl-k">return</span> <span class="pl-c1">len</span>(double_re.findall(val))
  199. val <span class="pl-k">=</span> <span class="pl-s"><span class="pl-pds">'</span><span class="pl-pds">'</span></span>.join(random.choice(string.ascii_letters) <span class="pl-k">for</span> i <span class="pl-k">in</span> <span class="pl-c1">range</span>(<span class="pl-c1">1000000</span>))
  200. <span class="pl-k">def</span> <span class="pl-en">test_pure_python</span>(<span class="pl-smi">benchmark</span>):
  201. benchmark(count_doubles, val)
  202. <span class="pl-k">def</span> <span class="pl-en">test_regex</span>(<span class="pl-smi">benchmark</span>):
  203. benchmark(count_doubles_regex, val)
  204. <span class="pl-k">def</span> <span class="pl-en">test_rust</span>(<span class="pl-smi">benchmark</span>): <span class="pl-c"># &lt;-- Benchmark the Rust version</span>
  205. benchmark(myrustlib.count_doubles, val)
  206. </pre>
  207. </div>
  208. <h1>Benchmark</h1>
  209. <div class="highlight highlight-source-shell">
  210. <pre>$ pytest doubles.py
  211. ==============================================================================
  212. platform linux -- Python 3.6.0, pytest-3.2.3, py-1.4.34, pluggy-0.4.
  213. benchmark: 3.1.1 (defaults: timer=time.perf_counter disable_gc=False min_round
  214. rootdir: /Projects/rustpy, inifile:
  215. plugins: benchmark-3.1.1
  216. collected 3 items
  217. doubles.py ...
  218. -----------------------------------------------------------------------------
  219. Name (time <span class="pl-k">in</span> ms) Min Max Mean
  220. -----------------------------------------------------------------------------
  221. test_rust 2.5555 (1.0) 2.9296 (1.0) 2.6085 (1.0)
  222. test_regex 25.6049 (10.02) 27.2190 (9.29) 25.8876 (9.92)
  223. test_pure_python 52.9428 (20.72) 56.3666 (19.24) 53.9732 (20.69)
  224. -----------------------------------------------------------------------------</pre>
  225. </div>
  226. <p>Lets take the <code>Mean</code> for comparison:</p>
  227. <ul>
  228. <li><strong>Rust</strong> &#8211; 2.6085 <strong>&lt;&#8211; less is better</strong></li>
  229. <li><strong>Regexp</strong> &#8211; 25.8876</li>
  230. <li><strong>Python Zip</strong> &#8211; 53.9732</li>
  231. </ul>
  232. <p>Rust implementation can be <strong>10x</strong> faster than Python Regex and <strong>21x</strong> faster than Pure Python Version.</p>
  233. <blockquote><p>Interesting that <strong>Regex</strong> version is only 2x faster than Pure Python 🙂</p></blockquote>
  234. <blockquote><p>NOTE: That numbers makes sense only for this particular scenario, for other cases that comparison may be different.</p></blockquote>
  235. <h1></h1>
  236. <h1>Updates and Improvements</h1>
  237. <p>After this article has been published I got some comments on <a href="https://www.reddit.com/r/Python/comments/7dct9v/use_rust_to_write_python_modules/">r/python</a> and also on <a href="https://www.reddit.com/r/rust/comments/7dctmp/red_hat_developers_blog_speed_up_your_python/">r/rust</a></p>
  238. <p>The contributions came as <a href="https://github.com/rochacbruno/rust-python-example/pulls?utf8=%E2%9C%93&amp;q=is%3Apr">Pull Requests</a> and you can send a new if you think the functions can be improved.</p>
  239. <p>Thanks to: <a href="https://github.com/cuviper">Josh Stone</a> we got a better implementation for Rust which iterates the string only once and also the Python equivalent.</p>
  240. <p>Thanks to: <a href="https://github.com/purple-pixie">Purple Pixie</a> we got a Python implementation using <code>itertools</code>, however this version is not performing any better and still needs improvements.</p>
  241. <h2><a id="user-content-iterating-only-once" class="anchor" href="https://github.com/rochacbruno/rust-python-example#iterating-only-once"></a>Iterating only once</h2>
  242. <div class="highlight highlight-source-rust">
  243. <pre><span class="pl-k">fn</span> <span class="pl-en">count_doubles_once</span>(_py: Python, val: <span class="pl-k">&amp;</span><span class="pl-k">str</span>) -&gt; PyResult&lt;<span class="pl-k">u64</span>&gt; {
  244. <span class="pl-k">let</span> <span class="pl-k">mut</span> total <span class="pl-k">=</span> <span class="pl-c1">0u64</span>;
  245. <span class="pl-k">let</span> <span class="pl-k">mut</span> chars <span class="pl-k">=</span> val.<span class="pl-en">chars</span>();
  246. <span class="pl-k">if</span> <span class="pl-k">let</span> <span class="pl-c1">Some</span>(<span class="pl-k">mut</span> c1) <span class="pl-k">=</span> chars.<span class="pl-en">next</span>() {
  247. <span class="pl-k">for</span> c2 <span class="pl-k">in</span> chars {
  248. <span class="pl-k">if</span> c1 <span class="pl-k">==</span> c2 {
  249. total <span class="pl-k">+=</span> <span class="pl-c1">1</span>;
  250. }
  251. c1 <span class="pl-k">=</span> c2;
  252. }
  253. }
  254. <span class="pl-c1">Ok</span>(total)
  255. }</pre>
  256. </div>
  257. <div class="highlight highlight-source-python">
  258. <pre><span class="pl-k">def</span> <span class="pl-en">count_doubles_once</span>(<span class="pl-smi">val</span>):
  259. total <span class="pl-k">=</span> <span class="pl-c1">0</span>
  260. chars <span class="pl-k">=</span> <span class="pl-c1">iter</span>(val)
  261. c1 <span class="pl-k">=</span> <span class="pl-c1">next</span>(chars)
  262. <span class="pl-k">for</span> c2 <span class="pl-k">in</span> chars:
  263. <span class="pl-k">if</span> c1 <span class="pl-k">==</span> c2:
  264. total <span class="pl-k">+=</span> <span class="pl-c1">1</span>
  265. c1 <span class="pl-k">=</span> c2
  266. <span class="pl-k">return</span> total</pre>
  267. </div>
  268. <h2><a id="user-content-python-with-itertools" class="anchor" href="https://github.com/rochacbruno/rust-python-example#python-with-itertools"></a>Python with itertools</h2>
  269. <div class="highlight highlight-source-python">
  270. <pre><span class="pl-k">import</span> itertools
  271. <span class="pl-k">def</span> <span class="pl-en">count_doubles_itertools</span>(<span class="pl-smi">val</span>):
  272. c1s, c2s <span class="pl-k">=</span> itertools.tee(val)
  273. <span class="pl-c1">next</span>(c2s, <span class="pl-c1">None</span>)
  274. total <span class="pl-k">=</span> <span class="pl-c1">0</span>
  275. <span class="pl-k">for</span> c1, c2 <span class="pl-k">in</span> <span class="pl-c1">zip</span>(c1s, c2s):
  276. <span class="pl-k">if</span> c1 <span class="pl-k">==</span> c2:
  277. total <span class="pl-k">+=</span> <span class="pl-c1">1</span>
  278. <span class="pl-k">return</span> total</pre>
  279. </div>
  280. <h3>Why not C/C++/Nim/Go/Ĺua/PyPy/{other language}?</h3>
  281. <p>Ok, that is not the purpose of this post, this post was never about comparing <code>Rust</code> X <code>other language</code>, this post was specifically about <strong>how to use Rust to extend and speed up Python</strong> and by doing that it means you have a good reason to choose Rust instead of <code>other language</code> or by its ecosystem or by its safety and tooling or just to follow the hype, or simply because you like Rust doesn&#8217;t matter the reason, this post is here to show how to use it with <strong>Python</strong>.</p>
  282. <p>I (personally) may say that Rust is more <code>future proof</code> as it is new and there are lots of improvements to come, also because of its ecosystem, tooling, and community and also because I feel comfortable with Rust syntax, I really like it!</p>
  283. <p>So, as expected people started complaining about the use of other languages and it becomes a sort of benchmark, and I think it is cool!</p>
  284. <p>So as part of my request for improvements some people on <a href="https://news.ycombinator.com/item?id=15719254" rel="nofollow">Hacker News</a> also sent ideas, <a href="https://github.com/martinxyz">martinxyz</a> sent an implementation using C and SWIG that performed very well.</p>
  285. <p>C Code (swig boilerplate omitted)</p>
  286. <div class="highlight highlight-source-c">
  287. <pre><span class="pl-c1">uint64_t</span> <span class="pl-en">count_byte_doubles</span>(<span class="pl-k">char</span> * str) {
  288. <span class="pl-c1">uint64_t</span> count = <span class="pl-c1">0</span>;
  289. <span class="pl-k">while</span> (str[<span class="pl-c1">0</span>] &amp;&amp; str[<span class="pl-c1">1</span>]) {
  290. <span class="pl-k">if</span> (str[<span class="pl-c1">0</span>] == str[<span class="pl-c1">1</span>]) count++;
  291. str++;
  292. }
  293. <span class="pl-k">return</span> count;
  294. }</pre>
  295. </div>
  296. <p>And our fellow Red Hatter <a href="https://github.com/cuviper">Josh Stone</a> improved the Rust implementation again by replacing <code>chars</code> with <code>bytes</code> so it is a fair competition with <code>C</code> as C is comparing bytes instead of Unicode chars.</p>
  297. <div class="highlight highlight-source-rust">
  298. <pre><span class="pl-k">fn</span> <span class="pl-en">count_doubles_once_bytes</span>(_py: Python, val: <span class="pl-k">&amp;</span><span class="pl-k">str</span>) -&gt; PyResult&lt;<span class="pl-k">u64</span>&gt; {
  299. <span class="pl-k">let</span> <span class="pl-k">mut</span> total <span class="pl-k">=</span> <span class="pl-c1">0u64</span>;
  300. <span class="pl-k">let</span> <span class="pl-k">mut</span> chars <span class="pl-k">=</span> val.<span class="pl-en">bytes</span>();
  301. <span class="pl-k">if</span> <span class="pl-k">let</span> <span class="pl-c1">Some</span>(<span class="pl-k">mut</span> c1) <span class="pl-k">=</span> chars.<span class="pl-en">next</span>() {
  302. <span class="pl-k">for</span> c2 <span class="pl-k">in</span> chars {
  303. <span class="pl-k">if</span> c1 <span class="pl-k">==</span> c2 {
  304. total <span class="pl-k">+=</span> <span class="pl-c1">1</span>;
  305. }
  306. c1 <span class="pl-k">=</span> c2;
  307. }
  308. }
  309. <span class="pl-c1">Ok</span>(total)
  310. }</pre>
  311. </div>
  312. <p>There are also ideas to compare Python <code>list comprehension</code> and <code>numpy</code> so I included here</p>
  313. <p>Numpy:</p>
  314. <div class="highlight highlight-source-python">
  315. <pre><span class="pl-k">import</span> numpy <span class="pl-k">as</span> np
  316. <span class="pl-k">def</span> <span class="pl-en">count_double_numpy</span>(<span class="pl-smi">val</span>):
  317. ng<span class="pl-k">=</span>np.fromstring(val,<span class="pl-v">dtype</span><span class="pl-k">=</span>np.byte)
  318. <span class="pl-k">return</span> np.sum(ng[:<span class="pl-k">-</span><span class="pl-c1">1</span>]<span class="pl-k">==</span>ng[<span class="pl-c1">1</span>:])</pre>
  319. </div>
  320. <p>List comprehension</p>
  321. <div class="highlight highlight-source-python">
  322. <pre><span class="pl-k">def</span> <span class="pl-en">count_doubles_comprehension</span>(<span class="pl-smi">val</span>):
  323. <span class="pl-k">return</span> <span class="pl-c1">sum</span>(<span class="pl-c1">1</span> <span class="pl-k">for</span> c1, c2 <span class="pl-k">in</span> <span class="pl-c1">zip</span>(val, val[<span class="pl-c1">1</span>:]) <span class="pl-k">if</span> c1 <span class="pl-k">==</span> c2)</pre>
  324. </div>
  325. <p>The complete test case is on repository <code>test_all.py</code> file.</p>
  326. <h2><a id="user-content-new-results" class="anchor" href="https://github.com/rochacbruno/rust-python-example#new-results"></a>New Results</h2>
  327. <p><strong>NOTE</strong>: Have in mind that the comparison was done in the same environment and may have some differences if run in a different environment using another compiler and/or different tags.</p>
  328. <div class="highlight highlight-source-shell">
  329. <pre>-------------------------------------------------------------------------------------------------
  330. Name (time <span class="pl-k">in</span> us) Min Max Mean
  331. -------------------------------------------------------------------------------------------------
  332. <strong>test_rust_bytes_once</strong> 476.7920 (1.0) 830.5610 (1.0) <strong>486.6116 (1.0)</strong>
  333. <strong>test_c_swig_bytes_once</strong> 795.3460 (1.67) 1,504.3380 (1.81) <strong>827.3898 (1.70)</strong>
  334. test_rust_once 985.9520 (2.07) 1,483.8120 (1.79) 1,017.4251 (2.09)
  335. <strong>test_numpy</strong> 1,001.3880 (2.10) 2,461.1200 (2.96) <strong>1,274.8132 (2.62)</strong>
  336. test_rust 2,555.0810 (5.36) 3,066.0430 (3.69) 2,609.7403 (5.36)
  337. test_regex 24,787.0670 (51.99) 26,513.1520 (31.92) 25,333.8143 (52.06)
  338. test_pure_python_once 36,447.0790 (76.44) 48,596.5340 (58.51) 38,074.5863 (78.24)
  339. <strong>test_python_comprehension</strong> 49,166.0560 (103.12) 50,832.1220 (61.20) <strong>49,699.2122 (102.13)</strong>
  340. test_pure_python 49,586.3750 (104.00) 50,697.3780 (61.04) 50,148.6596 (103.06)
  341. test_itertools 56,762.8920 (119.05) 69,660.0200 (83.87) 58,402.9442 (120.02)
  342. -------------------------------------------------------------------------------------------------
  343. </pre>
  344. </div>
  345. <ul>
  346. <li>The <code>new Rust implementation comparing bytes</code> is <strong>2x better</strong> than the old comparing Unicode <code>chars</code></li>
  347. <li>The <code>Rust</code> version is still better than the <code>C</code> using SWIG</li>
  348. <li><code>Rust</code> comparing <code>unicode chars</code> is still better than <code>numpy</code></li>
  349. <li>However <code>Numpy</code> is better than the <code>first Rust implementation</code> which had the problem of <strong>double iteration over the unicode chars</strong></li>
  350. <li>Using a <code>list comprehension</code> does not make significative difference than using <code>pure Python</code></li>
  351. </ul>
  352. <blockquote><p>NOTE: If you want to propose changes or improvements send a PR here: <a href="https://github.com/rochacbruno/rust-python-example/">https://github.com/rochacbruno/rust-python-example/</a></p></blockquote>
  353. <h1><a id="user-content-conclusion" class="anchor" href="https://github.com/rochacbruno/rust-python-example#conclusion"></a>Conclusion</h1>
  354. <p>Back to the purpose of this post &#8220;How to Speed Up your Python with Rust&#8221; we started with:</p>
  355. <p>&#8211; <strong>Pure Python</strong> function taking <strong>102 ms.<br />
  356. </strong>&#8211; Improved with <strong>Numpy </strong>(which is implemented in C) to take <strong>3 ms.<br />
  357. </strong>&#8211; Ended with <strong>Rust</strong> taking <strong>1 ms.</strong></p>
  358. <p>In this example <strong>Rust</strong> performed <strong>100x faster</strong> than our <strong>Pure </strong>Python.</p>
  359. <p><code>Rust</code> will not magically save you, you must know the language to be able to implement the clever solution and once implemented in the right it worth as much as C in terms of performance and also comes with amazing tooling, ecosystem, community and safety bonuses.</p>
  360. <p><code>Rust</code> may not be <strong>yet</strong> the <code>general purpose language</code> of choice by its level of complexity and may not be the better choice yet to write common simple <code>applications</code> such as <code>web</code> sites and <code>test automation</code> scripts.</p>
  361. <p>However, for <code>specific parts</code> of the project where Python is known to be the bottleneck and your natural choice would be implementing a <code>C/C++</code> extension, writing this extension in Rust seems easy and better to maintain.</p>
  362. <p>There are still many improvements to come in Rust and lots of others crates to offer <code>Python &lt;--&gt; Rust</code> integration. Even if you are not including the language in your tool belt right now, it is really worth to keep an eye open to the future!</p>
  363. <h2><a id="user-content-credits" class="anchor" href="https://github.com/rochacbruno/rust-python-example#credits"></a>References</h2>
  364. <p>The code snippets for the examples showed here are available in GitHub repo: <a href="https://github.com/rochacbruno/rust-python-example">https://github.com/rochacbruno/rust-python-example</a>.</p>
  365. <p>The examples in this publication are inspired by <code>Extending Python with Rust</code> talk by <strong>Samuel Cormier-Iijima</strong> in <strong>Pycon Canada</strong>. video here: <a href="https://www.youtube.com/watch?v=-ylbuEzkG4M">https://www.youtube.com/watch?v=-ylbuEzkG4M</a>.</p>
  366. <p>Also by <code>My Python is a little Rust-y</code> by <strong>Dan Callahan</strong> in <strong>Pycon Montreal</strong>. video here: <a href="https://www.youtube.com/watch?v=3CwJ0MH-4MA">https://www.youtube.com/watch?v=3CwJ0MH-4MA</a>.</p>
  367. <p>Other references:</p>
  368. <ul>
  369. <li><a href="https://github.com/mitsuhiko/snaek">https://github.com/mitsuhiko/snaek</a></li>
  370. <li><a href="https://github.com/PyO3/pyo3">https://github.com/PyO3/pyo3</a></li>
  371. <li><a href="https://pypi.python.org/pypi/setuptools-rust">https://pypi.python.org/pypi/setuptools-rust</a></li>
  372. <li><a href="https://github.com/mckaymatt/cookiecutter-pypackage-rust-cross-platform-publish">https://github.com/mckaymatt/cookiecutter-pypackage-rust-cross-platform-publish</a></li>
  373. <li><a href="http://jakegoulding.com/rust-ffi-omnibus/">http://jakegoulding.com/rust-ffi-omnibus/</a></li>
  374. <li><a href="https://github.com/urschrei/polylabel-rs/blob/master/src/ffi.rs">https://github.com/urschrei/polylabel-rs/blob/master/src/ffi.rs</a></li>
  375. <li><a href="https://bheisler.github.io/post/calling-rust-in-python/">https://bheisler.github.io/post/calling-rust-in-python/</a></li>
  376. <li><a href="https://github.com/saethlin/rust-lather">https://github.com/saethlin/rust-lather</a></li>
  377. </ul>
  378. <p><strong>Join Community:</strong></p>
  379. <p>Join Rust community, you can find group links in <a href="https://www.rust-lang.org/en-US/community.html">https://www.rust-lang.org/en-US/community.html</a>.</p>
  380. <p><strong>If you speak Portuguese,</strong> I recommend you to join <a href="https://t.me/rustlangbr">https://t.me/rustlangbr</a> and there is the <a href="http://bit.ly/canalrustbr">http://bit.ly/canalrustbr</a> on Youtube.</p>
  381. <h2><a id="user-content-author" class="anchor" href="https://github.com/rochacbruno/rust-python-example#author"></a>Author</h2>
  382. <p><strong>Bruno Rocha</strong></p>
  383. <ul>
  384. <li>Senior Quality Engineer at <strong>Red Hat</strong></li>
  385. <li>Teaching Python and Flask at <a href="http://CursoDePython.com.br">CursoDePython.com.br</a></li>
  386. <li>Fellow Member of Python Software Foundation</li>
  387. <li>Member of RustBR study group</li>
  388. </ul>
  389. <p>More info: <a href="http://about.me/rochacbruno">http://about.me/rochacbruno</a> and <a href="http://brunorocha.org/">http://brunorocha.org</a></p>
  390. <hr />
  391. <p><b>Whether you are new to Containers or have experience, downloading this </b><a href="https://developers.redhat.com/promotions/docker-cheatsheet/"><b>cheat sheet</b></a><b> can assist you when encountering tasks you haven’t done lately. </b></p>