title: Speed up your Python using Rust
url: https://developers.redhat.com/blog/2017/11/16/speed-python-using-rust/
hash_url: 6a759885012094d09d4b2d9f8f96fbbc

<h2>What is Rust?</h2>
<p><strong>Rust</strong> is a systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety.</p>
<p><strong>Featuring</strong></p>
<ul>
<li>zero-cost abstractions</li>
<li>move semantics</li>
<li>guaranteed memory safety</li>
<li>threads without data races</li>
<li>trait-based generics</li>
<li>pattern matching</li>
<li>type inference</li>
<li>minimal runtime</li>
<li>efficient C bindings</li>
</ul>
<p>Description is taken from <a href="http://rust-lang.org">rust-lang.org</a>.</p>
<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>
<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>
<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 />
<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 />
<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>
<p>There is a bunch of Rust packages out there to help you extending Python with Rust.</p>
<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>
<h3><em>See a complete reference list at the bottom of this article.</em></h3>
<p>Let&#8217;s<strong> see it in action</strong></p>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<h2><a id="user-content-example" class="anchor" href="https://github.com/rochacbruno/rust-python-example#example"></a>Example</h2>
<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>
<div class="highlight highlight-source-shell">
<pre><span class="pl-c"># How many subsequent-repeated group of chars are in the given string? </span>
abCCdeFFghiJJklmnopqRRstuVVxyZZ... {millions of chars here}
  1   2    3        4    5   6</pre>
</div>
<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>
<div class="highlight highlight-source-shell">
<pre><span class="pl-c"># Using a Python3.6 environment</span>
$ pip3 install pytest pytest-benchmark
</pre>
</div>
<p>Then write a new Python program called <code>doubles.py</code></p>
<div class="highlight highlight-source-python">
<pre><span class="pl-k">import</span> re
<span class="pl-k">import</span> string
<span class="pl-k">import</span> random

<span class="pl-c"># Python ZIP version</span>
<span class="pl-k">def</span> <span class="pl-en">count_doubles</span>(<span class="pl-smi">val</span>):
    total <span class="pl-k">=</span> <span class="pl-c1">0
</span>    # there is an improved version later on this post
    <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:
            total <span class="pl-k">+=</span> <span class="pl-c1">1</span>
    <span class="pl-k">return</span> total


<span class="pl-c"># Python REGEXP version</span>
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>)

<span class="pl-k">def</span> <span class="pl-en">count_doubles_regex</span>(<span class="pl-smi">val</span>):
    <span class="pl-k">return</span> <span class="pl-c1">len</span>(double_re.findall(val))


<span class="pl-c"># Benchmark it</span>
<span class="pl-c"># generate 1M of random letters to test it</span>
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>))

<span class="pl-k">def</span> <span class="pl-en">test_pure_python</span>(<span class="pl-smi">benchmark</span>):
    benchmark(count_doubles, val)

<span class="pl-k">def</span> <span class="pl-en">test_regex</span>(<span class="pl-smi">benchmark</span>):
    benchmark(count_doubles_regex, val)</pre>
</div>
<p>Run <strong>pytest</strong> to compare:</p>
<div class="highlight highlight-source-shell">
<pre>$ pytest doubles.py
=============================================================================
platform linux -- Python 3.6.0, pytest-3.2.3, py-1.4.34, pluggy-0.4.
benchmark: 3.1.1 (defaults: timer=time.perf_counter disable_gc=False min_roun
rootdir: /Projects/rustpy, inifile:
plugins: benchmark-3.1.1
collected 2 items

doubles.py ..


-----------------------------------------------------------------------------
Name (time <span class="pl-k">in</span> ms)         Min                Max               Mean
-----------------------------------------------------------------------------
test_regex            24.6824 (1.0)      32.3960 (1.0)      27.0167 (1.0)
test_pure_python      51.4964 (2.09)     62.5680 (1.93)     52.8334 (1.96)
-----------------------------------------------------------------------------
</pre>
</div>
<p>Lets take the <code>Mean</code> for comparison:</p>
<ul>
<li><strong>Regexp</strong> &#8211; 27.0167 <strong>&lt;&#8211; less is better</strong></li>
<li><strong>Python Zip</strong> &#8211; 52.8334</li>
</ul>
<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>
<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>
<blockquote><p><strong>crate</strong> is how we call Rust Packages.</p></blockquote>
<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>
<blockquote><p>I used <code>rustc 1.21.0</code></p></blockquote>
<p>In the same folder run:</p>
<div class="highlight highlight-source-shell">
<pre>cargo new pyext-myrustlib</pre>
</div>
<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>
<h2><a id="user-content-edit-cargotoml" class="anchor" href="https://github.com/rochacbruno/rust-python-example#edit-cargotoml"></a>Edit Cargo.toml</h2>
<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>
<div class="highlight highlight-source-toml">
<pre>[<span class="pl-en">package</span>]
<span class="pl-smi">name</span> = <span class="pl-s"><span class="pl-pds">"</span>pyext-myrustlib<span class="pl-pds">"</span></span>
<span class="pl-smi">version</span> = <span class="pl-s"><span class="pl-pds">"</span>0.1.0<span class="pl-pds">"</span></span>
<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>]

[<span class="pl-en">lib</span>]
<span class="pl-smi">name</span> = <span class="pl-s"><span class="pl-pds">"</span>myrustlib<span class="pl-pds">"</span></span>
<span class="pl-smi">crate-type</span> = [<span class="pl-s"><span class="pl-pds">"</span>dylib<span class="pl-pds">"</span></span>]

[<span class="pl-en">dependencies</span>.<span class="pl-en">cpython</span>]
<span class="pl-smi">version</span> = <span class="pl-s"><span class="pl-pds">"</span>0.1<span class="pl-pds">"</span></span>
<span class="pl-smi">features</span> = [<span class="pl-s"><span class="pl-pds">"</span>extension-module<span class="pl-pds">"</span></span>]</pre>
</div>
<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>
<p>What we need to do:</p>
<ol>
<li>Import all macros from <code>cpython</code> crate.</li>
<li>Take <code>Python</code> and <code>PyResult</code> types from CPython into our lib scope.</li>
<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:
<ul>
<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>
<li>Receives a <code>&amp;str</code> typed <code>val</code> as reference.</li>
<li>Returns a <code>PyResult</code> which is a type that allows the rise of Python exceptions.</li>
<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>
</ul>
</li>
<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>.
<ul>
<li>Attention to the names <strong>lib</strong>myrustlib, <strong>initlib</strong>myrustlib, and <strong>PyInit.</strong></li>
<li>We also use the <code>try!</code> macro, which is the equivalent to Python&#8217;s<code>try.. except</code>.</li>
<li>Return <code>Ok(())</code> &#8211; The <code>()</code> is an empty result tuple, the equivalent of <code>None</code> in Python.</li>
</ul>
</li>
</ol>
<div class="highlight highlight-source-rust">
<pre>#[macro_use]
<span class="pl-k">extern</span> <span class="pl-k">crate</span> cpython;

<span class="pl-k">use</span> cpython<span class="pl-k">::</span>{Python, PyResult};

<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; {
    <span class="pl-k">let</span> <span class="pl-k">mut</span> total <span class="pl-k">=</span> <span class="pl-c1">0u64</span>;

    // There is an improved version later on this post
    <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>)) {
        <span class="pl-k">if</span> c1 <span class="pl-k">==</span> c2 {
            total <span class="pl-k">+=</span> <span class="pl-c1">1</span>;
        }
    }

    <span class="pl-c1">Ok</span>(total)
}

<span class="pl-en">py_module_initializer!</span>(libmyrustlib, initlibmyrustlib, PyInit_myrustlib, <span class="pl-k">|</span>py, m <span class="pl-k">|</span> {
    <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>));
    <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>))));
    <span class="pl-c1">Ok</span>(())
});
</pre>
</div>
<h2>Now let&#8217;s build it with cargo</h2>
<div class="highlight highlight-source-shell">
<pre>$ cargo build --release
    Finished release [optimized] target(s) <span class="pl-k">in</span> 0.0 secs

$ ls -la target/release/libmyrustlib<span class="pl-k">*</span>
target/release/libmyrustlib.d
target/release/libmyrustlib.so<span class="pl-k">*</span>  <span class="pl-k">&lt;</span>-- Our dylib is here</pre>
</div>
<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>
<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>
<div class="highlight highlight-source-shell">
<pre>$ <span class="pl-c1">cd</span> ..
$ ls
doubles.py pyext-myrustlib/

$ cp pyext-myrustlib/target/release/libmyrustlib.so myrustlib.so

$ ls
doubles.py myrustlib.so pyext-myrustlib/</pre>
</div>
<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>
<p>&nbsp;</p></blockquote>
<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>
<p>Edit your <code>doubles.py</code> now importing our <code>Rust implemented</code> version and adding a <code>benchmark</code> for it.</p>
<div class="highlight highlight-source-python">
<pre><span class="pl-k">import</span> re
<span class="pl-k">import</span> string
<span class="pl-k">import</span> random
<span class="pl-k">import</span> myrustlib   <span class="pl-c">#  &lt;-- Import the Rust implemented module (myrustlib.so)</span>


<span class="pl-k">def</span> <span class="pl-en">count_doubles</span>(<span class="pl-smi">val</span>):
    <span class="pl-s"><span class="pl-pds">"""</span>Count repeated pair of chars ins a string<span class="pl-pds">"""</span></span>
    total <span class="pl-k">=</span> <span class="pl-c1">0</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:
            total <span class="pl-k">+=</span> <span class="pl-c1">1</span>
    <span class="pl-k">return</span> total


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>)


<span class="pl-k">def</span> <span class="pl-en">count_doubles_regex</span>(<span class="pl-smi">val</span>):
    <span class="pl-k">return</span> <span class="pl-c1">len</span>(double_re.findall(val))


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>))


<span class="pl-k">def</span> <span class="pl-en">test_pure_python</span>(<span class="pl-smi">benchmark</span>):
    benchmark(count_doubles, val)


<span class="pl-k">def</span> <span class="pl-en">test_regex</span>(<span class="pl-smi">benchmark</span>):
    benchmark(count_doubles_regex, val)


<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>
    benchmark(myrustlib.count_doubles, val)
</pre>
</div>
<h1>Benchmark</h1>
<div class="highlight highlight-source-shell">
<pre>$ pytest doubles.py
==============================================================================
platform linux -- Python 3.6.0, pytest-3.2.3, py-1.4.34, pluggy-0.4.
benchmark: 3.1.1 (defaults: timer=time.perf_counter disable_gc=False min_round
rootdir: /Projects/rustpy, inifile:
plugins: benchmark-3.1.1
collected 3 items

doubles.py ...


-----------------------------------------------------------------------------
Name (time <span class="pl-k">in</span> ms)         Min                Max               Mean
-----------------------------------------------------------------------------
test_rust              2.5555 (1.0)       2.9296 (1.0)       2.6085 (1.0)
test_regex            25.6049 (10.02)    27.2190 (9.29)     25.8876 (9.92)
test_pure_python      52.9428 (20.72)    56.3666 (19.24)    53.9732 (20.69)
-----------------------------------------------------------------------------</pre>
</div>
<p>Lets take the <code>Mean</code> for comparison:</p>
<ul>
<li><strong>Rust</strong> &#8211; 2.6085 <strong>&lt;&#8211; less is better</strong></li>
<li><strong>Regexp</strong> &#8211; 25.8876</li>
<li><strong>Python Zip</strong> &#8211; 53.9732</li>
</ul>
<p>Rust implementation can be <strong>10x</strong> faster than Python Regex and <strong>21x</strong> faster than Pure Python Version.</p>
<blockquote><p>Interesting that <strong>Regex</strong> version is only 2x faster than Pure Python 🙂</p></blockquote>
<blockquote><p>NOTE: That numbers makes sense only for this particular scenario, for other cases that comparison may be different.</p></blockquote>
<h1></h1>
<h1>Updates and Improvements</h1>
<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>
<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>
<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>
<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>
<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>
<div class="highlight highlight-source-rust">
<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; {
    <span class="pl-k">let</span> <span class="pl-k">mut</span> total <span class="pl-k">=</span> <span class="pl-c1">0u64</span>;

    <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>();
    <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>() {
        <span class="pl-k">for</span> c2 <span class="pl-k">in</span> chars {
            <span class="pl-k">if</span> c1 <span class="pl-k">==</span> c2 {
                total <span class="pl-k">+=</span> <span class="pl-c1">1</span>;
            }
            c1 <span class="pl-k">=</span> c2;
        }
    }

    <span class="pl-c1">Ok</span>(total)
}</pre>
</div>
<div class="highlight highlight-source-python">
<pre><span class="pl-k">def</span> <span class="pl-en">count_doubles_once</span>(<span class="pl-smi">val</span>):
    total <span class="pl-k">=</span> <span class="pl-c1">0</span>
    chars <span class="pl-k">=</span> <span class="pl-c1">iter</span>(val)
    c1 <span class="pl-k">=</span> <span class="pl-c1">next</span>(chars)
    <span class="pl-k">for</span> c2 <span class="pl-k">in</span> chars:
        <span class="pl-k">if</span> c1 <span class="pl-k">==</span> c2:
            total <span class="pl-k">+=</span> <span class="pl-c1">1</span>
        c1 <span class="pl-k">=</span> c2
    <span class="pl-k">return</span> total</pre>
</div>
<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>
<div class="highlight highlight-source-python">
<pre><span class="pl-k">import</span> itertools

<span class="pl-k">def</span> <span class="pl-en">count_doubles_itertools</span>(<span class="pl-smi">val</span>):
    c1s, c2s <span class="pl-k">=</span> itertools.tee(val)
    <span class="pl-c1">next</span>(c2s, <span class="pl-c1">None</span>)
    total <span class="pl-k">=</span> <span class="pl-c1">0</span>
    <span class="pl-k">for</span> c1, c2 <span class="pl-k">in</span> <span class="pl-c1">zip</span>(c1s, c2s):
        <span class="pl-k">if</span> c1 <span class="pl-k">==</span> c2:
            total <span class="pl-k">+=</span> <span class="pl-c1">1</span>
    <span class="pl-k">return</span> total</pre>
</div>
<h3>Why not C/C++/Nim/Go/Ĺua/PyPy/{other language}?</h3>
<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>
<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>
<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>
<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>
<p>C Code (swig boilerplate omitted)</p>
<div class="highlight highlight-source-c">
<pre><span class="pl-c1">uint64_t</span> <span class="pl-en">count_byte_doubles</span>(<span class="pl-k">char</span> * str) {
  <span class="pl-c1">uint64_t</span> count = <span class="pl-c1">0</span>;
  <span class="pl-k">while</span> (str[<span class="pl-c1">0</span>] &amp;&amp; str[<span class="pl-c1">1</span>]) {
    <span class="pl-k">if</span> (str[<span class="pl-c1">0</span>] == str[<span class="pl-c1">1</span>]) count++;
    str++;
  }
  <span class="pl-k">return</span> count;
}</pre>
</div>
<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>
<div class="highlight highlight-source-rust">
<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; {
    <span class="pl-k">let</span> <span class="pl-k">mut</span> total <span class="pl-k">=</span> <span class="pl-c1">0u64</span>;

    <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>();
    <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>() {
        <span class="pl-k">for</span> c2 <span class="pl-k">in</span> chars {
            <span class="pl-k">if</span> c1 <span class="pl-k">==</span> c2 {
                total <span class="pl-k">+=</span> <span class="pl-c1">1</span>;
            }
            c1 <span class="pl-k">=</span> c2;
        }
    }

    <span class="pl-c1">Ok</span>(total)
}</pre>
</div>
<p>There are also ideas to compare Python <code>list comprehension</code> and <code>numpy</code> so I included here</p>
<p>Numpy:</p>
<div class="highlight highlight-source-python">
<pre><span class="pl-k">import</span> numpy <span class="pl-k">as</span> np

<span class="pl-k">def</span> <span class="pl-en">count_double_numpy</span>(<span class="pl-smi">val</span>):
    ng<span class="pl-k">=</span>np.fromstring(val,<span class="pl-v">dtype</span><span class="pl-k">=</span>np.byte)
    <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>
</div>
<p>List comprehension</p>
<div class="highlight highlight-source-python">
<pre><span class="pl-k">def</span> <span class="pl-en">count_doubles_comprehension</span>(<span class="pl-smi">val</span>):
    <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>
</div>
<p>The complete test case is on repository <code>test_all.py</code> file.</p>
<h2><a id="user-content-new-results" class="anchor" href="https://github.com/rochacbruno/rust-python-example#new-results"></a>New Results</h2>
<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>
<div class="highlight highlight-source-shell">
<pre>-------------------------------------------------------------------------------------------------
Name (time <span class="pl-k">in</span> us)                     Min                    Max                   Mean
-------------------------------------------------------------------------------------------------
<strong>test_rust_bytes_once</strong>             476.7920 (1.0)         830.5610 (1.0)         <strong>486.6116 (1.0)</strong>
<strong>test_c_swig_bytes_once</strong>           795.3460 (1.67)      1,504.3380 (1.81)        <strong>827.3898 (1.70)</strong>
test_rust_once                   985.9520 (2.07)      1,483.8120 (1.79)      1,017.4251 (2.09)
<strong>test_numpy</strong>                     1,001.3880 (2.10)      2,461.1200 (2.96)      <strong>1,274.8132 (2.62)</strong>
test_rust                      2,555.0810 (5.36)      3,066.0430 (3.69)      2,609.7403 (5.36)
test_regex                    24,787.0670 (51.99)    26,513.1520 (31.92)    25,333.8143 (52.06)
test_pure_python_once         36,447.0790 (76.44)    48,596.5340 (58.51)    38,074.5863 (78.24)
<strong>test_python_comprehension</strong>     49,166.0560 (103.12)   50,832.1220 (61.20)    <strong>49,699.2122 (102.13)</strong>
test_pure_python              49,586.3750 (104.00)   50,697.3780 (61.04)    50,148.6596 (103.06)
test_itertools                56,762.8920 (119.05)   69,660.0200 (83.87)    58,402.9442 (120.02)
-------------------------------------------------------------------------------------------------
</pre>
</div>
<ul>
<li>The <code>new Rust implementation comparing bytes</code> is <strong>2x better</strong> than the old comparing Unicode <code>chars</code></li>
<li>The <code>Rust</code> version is still better than the <code>C</code> using SWIG</li>
<li><code>Rust</code> comparing <code>unicode chars</code> is still better than <code>numpy</code></li>
<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>
<li>Using a <code>list comprehension</code> does not make significative difference than using <code>pure Python</code></li>
</ul>
<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>
<h1><a id="user-content-conclusion" class="anchor" href="https://github.com/rochacbruno/rust-python-example#conclusion"></a>Conclusion</h1>
<p>Back to the purpose of this post &#8220;How to Speed Up your Python with Rust&#8221; we started with:</p>
<p>&#8211; <strong>Pure Python</strong> function taking <strong>102 ms.<br />
</strong>&#8211; Improved with <strong>Numpy </strong>(which is implemented in C) to take <strong>3 ms.<br />
</strong>&#8211; Ended with <strong>Rust</strong> taking <strong>1 ms.</strong></p>
<p>In this example <strong>Rust</strong> performed <strong>100x faster</strong> than our <strong>Pure </strong>Python.</p>
<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>
<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>
<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>
<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>
<h2><a id="user-content-credits" class="anchor" href="https://github.com/rochacbruno/rust-python-example#credits"></a>References</h2>
<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>
<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>
<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>
<p>Other references:</p>
<ul>
<li><a href="https://github.com/mitsuhiko/snaek">https://github.com/mitsuhiko/snaek</a></li>
<li><a href="https://github.com/PyO3/pyo3">https://github.com/PyO3/pyo3</a></li>
<li><a href="https://pypi.python.org/pypi/setuptools-rust">https://pypi.python.org/pypi/setuptools-rust</a></li>
<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>
<li><a href="http://jakegoulding.com/rust-ffi-omnibus/">http://jakegoulding.com/rust-ffi-omnibus/</a></li>
<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>
<li><a href="https://bheisler.github.io/post/calling-rust-in-python/">https://bheisler.github.io/post/calling-rust-in-python/</a></li>
<li><a href="https://github.com/saethlin/rust-lather">https://github.com/saethlin/rust-lather</a></li>
</ul>
<p><strong>Join Community:</strong></p>
<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>
<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>
<h2><a id="user-content-author" class="anchor" href="https://github.com/rochacbruno/rust-python-example#author"></a>Author</h2>
<p><strong>Bruno Rocha</strong></p>
<ul>
<li>Senior Quality Engineer at <strong>Red Hat</strong></li>
<li>Teaching Python and Flask at <a href="http://CursoDePython.com.br">CursoDePython.com.br</a></li>
<li>Fellow Member of Python Software Foundation</li>
<li>Member of RustBR study group</li>
</ul>
<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>
<hr />
<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>
