High-performance applications are often written in a lower-level language, such as C++ or Rust, rather than Python. The appeal of lower-level languages lies in the finer control they give over system resources, which can unlock a significant boost in performance.
With a foundational understanding of C++, from past work on microcontroller programming in C, I wanted to try moving a basic Python package to C++. As an Earth Science graduate working in software engineering, it seemed fitting to work on something geospatial. In previous projects I’ve used fmalina/blocl-bnglatlon1, which converts British National Grid (OSGB36) to latitude and longitude (WGS84). Whilst efficient, I suspected I could improve its performance by rewriting it in C++.
Aside from using constants, not much has been altered in the code. It is largely a straightforward translation to C++. The code is available on GitHub2.
Results
The following results were gathered over 100 runs.
| Item | CPU time (× 10⁻⁴ seconds) | Memory (MiB) |
|---|---|---|
| Python | 9.27458 | 20.828125 |
| C++ | 0.81958 | 20.812500 |
| Difference | 8.455 | ~0 |
- Duration: processing in C++ took about 91% less CPU time. That is a large gain for code that runs repeatedly.
- Memory: memory use was nearly identical between Python and C++, as expected.
Conclusion
This exercise was a useful lesson in the performance gains available from moving a small, CPU-bound module out of Python. The reduction in processing time shows how much language choice can matter in performance-critical code.
The result applies to this kind of tight numerical work. If a similar module is a measured bottleneck in your application, a direct translation to a lower-level language like C++ is worth considering.
Links
- https://github.com/fmalina/blocl-bnglatlon
- https://github.com/JKFSOM/bnglatlon-cpp