<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jay Sea on Medium]]></title>
        <description><![CDATA[Stories by Jay Sea on Medium]]></description>
        <link>https://medium.com/@Jayseabee?source=rss-952429012f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*18hiIYxfjyaYR6JU9feskA.jpeg</url>
            <title>Stories by Jay Sea on Medium</title>
            <link>https://medium.com/@Jayseabee?source=rss-952429012f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 15:33:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Jayseabee/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Rust & React — Part II]]></title>
            <link>https://medium.com/@Jayseabee/rust-react-part-ii-76c2ea60a80d?source=rss-952429012f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/76c2ea60a80d</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Jay Sea]]></dc:creator>
            <pubDate>Sat, 11 Mar 2023 06:46:06 GMT</pubDate>
            <atom:updated>2023-03-11T06:46:06.150Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rust &amp; React — Part II</h3><p>In <a href="https://medium.com/@Jayseabee/rust-react-part-i-3a33c3da9ca0">Rust &amp; React — Part I</a> we built an Rust based web server to generate Julia set images and a React app to trigger &amp; display them.</p><p>In part II we dig into the performance of the REST interface and see how we can get faster and more consistent performance using <a href="https://en.wikipedia.org/wiki/WebSocket">WebSockets</a>.</p><p>Source code available on <a href="https://github.com/jayseabee/rust-react-julia">GitHub jayseabee/rust-react-julia.git</a></p><h3>Julia Set Generation</h3><p>The Rust project has a test case to time how long it takes Rust to generate the Julia set image, at a specific resolution (800x500). Run it with: <br>cargo test julia_speed --release -- --show-output</p><p>On my system I get this:</p><pre>running 1 test<br>test julia::tests::julia_speed ... ok<br><br>successes:<br><br>---- julia::tests::julia_speed stdout ----<br>Julia set generation: cx: -0.707, cy: -0.158, time: 148.34ms<br>Julia set generation: cx: 0.567, cy: -0.424, time: 2.72ms<br>Julia set generation: cx: 0.006, cy: -0.736, time: 10.09ms<br>Julia set generation: cx: -0.545, cy: -0.215, time: 175.62ms<br>Julia set generation: cx: -0.070, cy: -0.679, time: 106.43ms<br>Julia set generation: cx: 0.041, cy: -0.716, time: 7.57ms<br>Julia set generation: cx: -0.841, cy: 0.695, time: 3.02ms<br>Julia set generation: cx: 0.359, cy: 0.648, time: 5.95ms<br>Julia set generation: cx: -0.259, cy: -0.834, time: 7.06ms<br>Julia set generation: cx: 0.240, cy: -0.104, time: 200.35m</pre><p>As you can see there is quite a bit of variability depending on the cx and cy parameters. To dig into the performance of the interface we are going to pick one fixed parameter set so we can isolate the overhead of the Rust &lt;-&gt; React interface.</p><p>For the case of cx = -0.3871, cy = -0.0018 we get timings of: 398ms in develop mode and 200ms in --release mode when running our test case using cargo test --release julia_save_png -- --show-output. That gives us a raw baseline on how long it takes to generate Julia set. Noting as we did in <a href="https://medium.com/@Jayseabee/rust-react-part-i-3a33c3da9ca0">Part I</a> we could easily improve this by threading the code, but here I am more interested in the interface than performance optimising the specific use case of Julia set generation.</p><p>Chrome’s developer tools, network tab provides some useful insight into the performance overhead of our REST call:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*4zzMks4Q0fHJcuVlt9VGxA.png" /></figure><p>We can see the “Waiting for server response”, green bar, matches how long it takes to create the image in Rust. And then we can see the “Content Download” takes about 49ms in this case. That is a quite a bit of overhead, particularly if you were targeting gaming applications.</p><h3>Websockets</h3><p>Ok, so lets see if we can do better if we replace REST calls with a W<a href="https://en.wikipedia.org/wiki/WebSocket">ebSocket</a> interface. On the Rust side we use <a href="https://crates.io/crates/actix-ws">Actix’s ws crate </a>to create a W<a href="https://github.com/jayseabee/rust-react-julia/blob/main/src/handler.rs">ebSocket handler</a>, called julia_ws.</p><pre>async fn julia_ws(req: HttpRequest, stream: web::Payload) -&gt; Result&lt;HttpResponse, Error&gt; {<br>    let (res, session, msg_stream) = actix_ws::handle(&amp;req, stream)?;<br><br>    // spawn websocket handler (and don&#39;t await it) so that <br>    // the response is returned immediately<br>    actix_rt::spawn(ws_handler::julia_ws(session, msg_stream));<br><br>    Ok(res)<br>}</pre><p>The asynchronous function <a href="https://github.com/jayseabee/rust-react-julia/blob/main/src/ws_handler.rs">julia_ws</a> runs a loop processing WebSocket messages.</p><pre>pub async fn julia_ws(mut session: actix_ws::Session, mut msg_stream: actix_ws::MessageStream) {<br>    log::info!(&quot;connected&quot;);<br><br>    let close_reason = loop {<br>        match msg_stream.next().await {<br>            Some(Ok(msg)) =&gt; {<br>                log::debug!(&quot;msg: {msg:?}&quot;);<br><br>                match msg {<br>                    Message::Text(text) =&gt; {<br>                        let julia_params: JuliaParams = serde_json::from_str(&amp;text).unwrap();<br>                        //println!(&quot;--- WS: value = {:#?}&quot;, julia_params);<br>                        let data = julia_generate(&amp;julia_params);<br>                        session.binary(data).await.unwrap();<br>                    }<br>...</pre><p>When the server receives a text message it extracts the Julia set parameters and generates the image, sending it back as a binary blob.</p><p>Worth noting, I have tried to keep it simple and have not included any functionality to manage the WebSocket connection in terms of timeouts. Its not really required for this use case and it is pretty easy to add on as this <a href="https://github.com/actix/examples/blob/master/websockets/echo-actorless/src/handler.rs">Actix example</a> demonstrates.</p><h3>React-side Sockets</h3><p>On the React side we create a new component called <a href="https://github.com/jayseabee/rust-react-julia/blob/main/react-app/src/components/wscanvas.js">wscanvas</a> which establishes a websocket with the server, using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket">WebSocket API</a>.</p><pre>...<br>let lsocket = new WebSocket(socket_url);<br>lsocket.binaryType = &quot;arraybuffer&quot;;<br>...</pre><p>Again, we use a series of useEffect hooks to step through the process of waiting for the socket to open up, generating a random set of parameters, processing the returned data and finally rendering the data to the canvas. We send these parameters like so:</p><pre>function sendParams() {<br>  if (socket &amp;&amp; params) {<br>    if (socket.readyState === 1) {<br>      let msg = {<br>        width: props.width,<br>        height: props.height,<br>        cx: params.cx,<br>        cy: params.cy,<br>      };<br>      socket.send(JSON.stringify(msg));<br>      const s = Date.now();<br>      setStartTime(s);<br>    } else {<br>      console.log(<br>        &quot;sendParams: socket not ready: state: &quot;,<br>        socket.readyState<br>      );<br>    }<br>  }</pre><p>We make sure the WebSocket is ready with socket.readyState === 1 (see <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState">readyState</a>). Then just encode our parameter object into a string and send it to the server. On the Rust side we use the <a href="https://crates.io/crates/serde_json">serde_json</a> crate to turn the string into a struct which is passed to the Rust julia_generate function.</p><p>When we set up the socket in the React component wscanvaswe also create the function to process the return data:</p><pre>lsocket.onmessage = (ev) =&gt; {<br>  if (ev.data instanceof ArrayBuffer) {<br>    setIsLoaded(true);<br>    const e = Date.now();<br>    setEndTime(e); <br><br>    setImage({<br>      status: &quot;healthy&quot;,<br>      data: new Uint8Array(ev.data),<br>    });<br>  } else {<br>    setError({ message: &quot;invalid data&quot; });<br>    console.log(ev.data);<br>  }</pre><p>We receive an event ev from the socket and we put that into our React image state, which in turn triggers the putImage function that renders the data into the canvas, as with our REST interface.</p><p>To switch from the REST interface to WebSockets all you need to do is change the api property on the juliacanvas component in <a href="https://github.com/jayseabee/rust-react-julia/blob/main/react-app/src/App.js">App.js</a>: set it to “websocket” to run WebSockets and anything else to run the REST GET interface.</p><pre>function App() {<br>  return (<br>    &lt;div className=&quot;App-body&quot;&gt;<br>      &lt;JuliaCanvas<br>        api=&quot;websocket&quot; // &quot;websocket&quot; or else runs get<br>        width={800}<br>        height={500}<br>        url=&quot;localhost&quot;<br>        port=&quot;8080&quot;<br>        className=&quot;App-canvas&quot;<br>      &gt;&lt;/JuliaCanvas&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Results</h3><p>Lets take a look at how well the WebSocket interface performs relative the REST interface. I have included both development (dev) and release timings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*cL2AyAn_3ZlYl2pLcOV_sQ.png" /><figcaption>Performance of REST and WebSocket interface for Julia Set generation</figcaption></figure><p>The solid blue line shows the performance (ms) of the REST interface over 10 runs. The solid green line shows the performance of the WebSocket interface. All runs used the same Julia set parameters and resolution (as above: -0.3871, cy = -0.0018, 800x500). As we have already seen in Rust alone it takes around 200ms to render the Julia set with this parameters set.</p><p>The REST interface (solid blue) has an overhead of around 60%, with a mean overall execution time of around 323ms, on our baseline of 200ms. And as the graph shows varies quite a bit from call to call (the standard deviation was 32ms).</p><p>The WebSocket interface (solid green) has a pretty minimal overhead of around 4%, with a mean overall execution time of 208ms, on our baseline of 200ms. And the performance overhead is also more consistent with a standard deviation of only 1ms across the 10 calls.</p><pre>Interface        Mean (std)     Perf Overhead% <br>----------------------------------------------    <br>REST           323ms (32ms)              61.5%<br>WebSocket      208ms ( 1ms)               4.0%     </pre><h3>Conclusion</h3><p>WebSockets are a more complex to get going but provide substantial performance improvements and are clearly the way to go if you need to get the best performance out of the Rust &lt;-&gt; React interface.</p><p>I see a lot of potential in this simple combination of Rust and React and hope that you can also find some utility for it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76c2ea60a80d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust & React — Part I]]></title>
            <link>https://medium.com/@Jayseabee/rust-react-part-i-3a33c3da9ca0?source=rss-952429012f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a33c3da9ca0</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[client-server]]></category>
            <dc:creator><![CDATA[Jay Sea]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 13:46:30 GMT</pubDate>
            <atom:updated>2023-03-11T06:46:42.017Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rust &amp; React — Part I</h3><h3>TLDR:</h3><ul><li>Combine Rust and React when you want beauty and speed in your life for applications in scientific computing, data science and gaming</li><li>We will build a Rust <a href="https://actix.rs/">Actix</a> server &amp; React app and get them to talk to each other</li><li>In <a href="https://medium.com/@Jayseabee/rust-react-part-ii-76c2ea60a80d">part II</a> we will take this framework further and switch up a gear with a websocket interface</li><li>Full source code available on <a href="https://github.com/jayseabee/rust-react-julia">GitHub jayseabee/rust-react-julia.git</a></li></ul><h3>Philosophy</h3><p>In software development raw computation and intuitive user interfaces are like yin and yang: two opposing but interconnected forces. In this article we are exploring how you can channel Rust and React to close the circle. And while we are at it, we might as well make something that looks pretty so we will be rendering Julia sets like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*oCwD9z9ZjUuJJ1cX8AiyWA.png" /></figure><p>Web based user interfaces are to my mind the most powerful and intuitive ways of communicating with ordinary humans. React is arguably the most popular web based UI framework. And Rust is the most fascinating of languages for raw computation providing bare metal performance on a par with C/C++ but with all the trimmings of a modern language (package management, built in frameworks for testing and concurrency etc).</p><p><a href="https://webassembly.org/">WebAssembly</a> (WASM) is an obvious way of bringing Rust and React together but I found it to be a bit limited due to constraints around concurrency. Some pretty common libraries like random number generators just don’t work smoothly in this context. So I started looking at Rust based services. In a lot of cases, it is also cleaner to separate out your raw compute workloads from your UI with a well defined interface.</p><p>But I would also point out <a href="https://yew.rs/">Yew</a>, which is a Rust framework for creating multi-threaded front-end web apps with WebAssembly. If you are looking for a pure Rust solution that might be a better fit.</p><h3>Rust Actix Web Server</h3><p>Actix is one of the most popular web server frameworks for Rust. We will use the <a href="https://crates.io/crates/actix">Actix crate</a> to listen for GET requests and generate a Julia sets in Rust. Here is an extract from <a href="https://github.com/jayseabee/rust-react/blob/main/src/main.rs">src/main.rs</a> showing how we set up Actix to handle a GET request.</p><pre>#[get(&quot;/julia-image&quot;)]<br>async fn get_julia_image(query: web::Query&lt;JuliaParams&gt;) -&gt; Result&lt;impl Responder&gt; {<br><br>    //println!(&quot;data: {:?}&quot;, query);<br>    let data = julia_generate(&amp;query.into_inner());<br><br>    let obj = ApiData {<br>        status: &quot;healthy&quot;.to_string(),<br>        data: data<br>    };<br>    Ok(web::Json(obj))<br>}</pre><p>This endpoint needs a set of parameters which we use to render our Julia set in <a href="https://github.com/jayseabee/rust-react-julia/blob/main/src/julia.rs">src/julia.rs</a>.</p><pre>#[derive(Clone, Debug, Deserialize)]<br>pub struct JuliaParams {<br>   pub width: u32,<br>   pub height: u32,<br>   pub cx: f32,<br>   pub cy: f32<br>}</pre><p>The Rust code to render the Julia set image is adapted from a <a href="https://rosettacode.org/wiki/Julia_set#Rust">Rosetta code snippet</a>. Its just single threaded: we could get improved performance by threading the generation of the Julia image. I will leave that for another day.</p><p>To get the server running type cargo run --release in the project directory . You can test the server by using curl on the command line:</p><pre>curl http://localhost:8080/julia-image\?width\=500\&amp;height\=500\&amp;cx\=1.2\&amp;cy\=1.3\</pre><p>The Actix server is running on the localhost on port 8080 and we are targeting the julia-image endpoint. We add the parameters width, height, cx, cy and iterations and the server should spew out a bunch of numbers for you. The data represents the RGBA pixel values of the Julia set image.</p><p>One of the features of Rust that I really like is the test framework. It really encourages you to develop test code while you build out your solution. Here is a test to generate the Julia set and save it as a PNG file (using the <a href="https://crates.io/crates/image">image crate</a>)</p><pre>  #[test]<br>  fn julia_test() {<br>      let start = Instant::now();<br><br>      let params = JuliaParams {<br>          width: 8000,<br>          height: 5000,<br>          cx: 0.28,<br>          cy: 0.008,<br>      };<br>      let v = julia_generate(&amp;params);<br>      println!(&quot;Julie set: {:?}&quot;, start.elapsed());<br><br>      assert!(save_image(v, params.width, params.height, &quot;julia-set.png&quot;.to_string()));<br>  }</pre><p>Try it with cargo test --release and it will run all the tests in the project and generate julia-set.png.</p><h3>React</h3><p>Ok, lets switch over to the React front end. We have setup a simple React project using the usual npx create-react-app react-app setup. We are just using Javascript to keep it simple/accessible but you would probably want to upgrade to Typescript for more complex projects.</p><p>App.js is pretty simple: it just renders a component called JuliaCanvas with a few parameters, including the location of the host and port of our Rust server:</p><pre>import &quot;./App.css&quot;;<br>import JuliaCanvas from &quot;./components/juliacanvas&quot;;<br><br>function App() {<br>  return (<br>    &lt;div className=&quot;App-body&quot;&gt;<br>      &lt;JuliaCanvas<br>        api=&quot;get&quot;<br>        width={800}<br>        height={500}<br>        url=&quot;localhost&quot;<br>        port=&quot;8080&quot;<br>        className=&quot;App-canvas&quot;<br>      &gt;&lt;/JuliaCanvas&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>The JuliaCanvacomponent is just a switch for selecting one of two different ways of getting data from the Rust server. In Part I we use a GET request and it chains through to react-app/src/components/getcanvas.js.</p><p>The GetCanvas component uses a Javascriptfetch api call to the julia-image API endpoint:</p><pre>let url = &quot;http://&quot; + props.url + &quot;:&quot; + props.port + &quot;/julia-image?&quot;;<br>let url_params = new URLSearchParams({<br>  width: props.width,<br>  height: props.height,<br>  cx: params.cx,<br>  cy: params.cy<br>});<br>const response = await fetch(url + url_params);<br>const data = await response.json();</pre><p>We use a sequence of useEffect hooks to send our request, wait for the response and then render the image.</p><p>We also generate some parameters for the Julia set using the <a href="https://github.com/jayseabee/rust-react-julia/blob/main/react-app/src/utils/rndParams.js">utils/rndParmas.js</a> code. This essentially sets cxto vary between -0.9 and 0.3 and cy to vary between -0.9 and 0.6. Why these ranges? Well take a look at Karl Sims excellent page on <a href="https://www.karlsims.com/julia.html">Understanding Julia and Mandelbrot sets</a> to see why.</p><pre>function rndParams() {<br>  return {<br>    cx: Math.random() * (0.9 - 0.3) - 0.9,<br>    cy: Math.random() * (0.9 + 0.6) - 0.9,<br>  };<br>}</pre><p>Whenever the props of the component are changed the first effect is triggered and re-calculates a new set of random parameters within our given ranges. This subsequently triggers the next which fetches the RGBA pixels from the Rust server and puts it into the image component state variable. A final effect, which is triggered when the image state changes, renders the pixels into a HTML canvas object:</p><pre>const putImage = async function (canvasRef, image) {<br>  try {<br>    const canvas = canvasRef.current;<br>    if (canvas &amp;&amp; image) {<br>      // in case the canvas hasn&#39;t been setup yet<br>      const context = canvas.getContext(&quot;2d&quot;);<br><br>      let canvasData = await context.getImageData(<br>        0,<br>        0,<br>        canvas.width,<br>        canvas.height<br>      );<br><br>      for (let i = 0; i &lt; canvasData.data.length; i++) {<br>        canvasData.data[i] = image.data[i];<br>      }<br><br>      context.putImageData(canvasData, 0, 0);<br>    }<br>  } catch (error) {<br>    console.error(error);<br>  }<br>};</pre><p>Here we get the existing canvas image (which starts off blank) and fill it with the data given to us by our Rust server. We then copy across the RGBA data we received from the GET request and put the data back into the canvas image to update it.</p><h3>Run</h3><p>To run the app from the github repo first get the rust server running: cargo run --release You should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*A7a4Ps8bxeoJpcyEN1IBRg.png" /></figure><p>Now go to the react-app directory and run: npm install followed by npm run build and finally server -s build to run the app in production mode. Or alternatively, after installing the node modules, just run npm start to run in development mode, if you are tinkering with the React code.</p><p>The app will run on localhost, port 3000 (i.e.http://localhost:3000/) and you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*_KwQE0zGiBTr2IUTvvrzeA.png" /></figure><p>If your Julia set isn’t so inspiring, don’t worry just press refresh. If you find a nice set of parameters and want to save the image use the cargo test function to generate a high res version.</p><p>In <a href="https://medium.com/@Jayseabee/rust-react-part-ii-76c2ea60a80d">part II</a> we will look at how you can get some more performance out of the Rust-React framework by replacing the RESTful API with websockets …</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a33c3da9ca0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KDTrees in Rust for Searching Spatial Data]]></title>
            <link>https://medium.com/@Jayseabee/kdtrees-in-rust-for-searching-spatial-data-a10cdd3466d0?source=rss-952429012f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a10cdd3466d0</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[kd-tree]]></category>
            <category><![CDATA[spatial-analysis]]></category>
            <dc:creator><![CDATA[Jay Sea]]></dc:creator>
            <pubDate>Sat, 03 Sep 2022 11:55:24 GMT</pubDate>
            <atom:updated>2022-09-04T04:36:06.872Z</atom:updated>
            <content:encoded><![CDATA[<p>I was looking to solve the following problem in rust for a project I was working on:</p><ul><li>Store point data in a bucket — each point has an attribute value</li><li>For any new point efficiently find the closest neighbouring points and their associated attribute values</li></ul><p>A bit of googling led me to k<a href="https://en.wikipedia.org/wiki/K-d_tree">-d trees</a>: a space partitioning data structure designed for finding nearest neighbours(O(log N) for insertion and look up). And the rust crate <a href="https://crates.io/crates/kdtree">kdtree</a> is popular with &gt; 150k downloads.</p><p>Ok, lets create a new rust project with cargo new kdtree and then add <a href="https://crates.io/crates/kdtree">kdtree</a> to the dependency section in cargo.toml. I am going to create some unit tests in main.rs to test stuff out:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87d85c99124badd4a9e566cc4b5270b2/href">https://medium.com/media/87d85c99124badd4a9e566cc4b5270b2/href</a></iframe><p>To run this type: cargo test kdtree_dist2d -- --show-output in the kdtree rust project directory. The result is:</p><pre>...<br>---- tests::kdtree_dist2d stdout ----<br>distance: 0.08, attribute: 1<br>distance: 1.28, attribute: 5<br>...</pre><p>The output indicates that point p3 is closest to p2 which has an attribute of 1: all good. It’s easy to extend this example to 3D. Just change the constructor to 3, pass a vector with 3 elements.</p><p>Also, we can use more complex attributes: you can pass a float or another type in as the attribute.</p><p>The next challenge is when you want to integrate the kdtree structure into some more useful code, inside a rust struct. To do that we need to be more specific about what types we will use with the kdtree. In the following example, we populate 100,000 random points into the tree and then benchmark how long it takes us to retrieve the clostest n points to a random position in query_bench</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08ef731c67c8ff7d7f0c949d03277a50/href">https://medium.com/media/08ef731c67c8ff7d7f0c949d03277a50/href</a></iframe><p>To use the benchmarking feature make you have to switch to the nightly release of the rust compiler using this command: rustup default nightly</p><p>Then you can run cargo bench and it will generate something like this:</p><pre>...<br>running 1 test<br>test tests::kdtree_struct ... bench:       1,498 ns/iter (+/- 466)<br>...</pre><p>So that is about 0.0015 milliseconds per point: or 1.5ms to look up 1,000 points. i.e. not slow.</p><p>So there you go. Hope that helps you get up and running with this very useful rust library. Kudos to <a href="https://crates.io/users/mrhooray">Rui Hu</a> (aka mrhorray).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a10cdd3466d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>