Timing Python/C/Rust on a Raspberry Pi
Big fat warning: Crude benchmarks like what you will see here should be used strictly for entertainment purpose!
I believe Rust will soon become a natural choice for programming embedded platforms like the Raspberry Pi. Look at what the Tessel guys are doing.
Getting Rust running on the Raspberry Pi is easy, just use rustup!
If you would like to read just one book on the Rpi, this is it:
While reading this book, I came upon this program which may be used for measuring performance of numerical code ( Rpi 3, code compiled with gcc -O3):
#include <stdio.h>
#include <math.h>
double integrate(double a, double b, double n)
{
int i;
double dx = (b - a) / n;
double sum = 0.0;
for(i = 0; i < n; i++) {
sum += sin(a + i*dx);
}
return sum*dx;
}
main()
{
printf("%f\n", integrate(0, M_PI, 1000000));
}
Here is the output obtained by running the time command:
2.000000
real 0m0.226s
user 0m0.220s
sys 0m0.000s
You can expect to see something between 0.2 to 0.3 seconds.
Here is the Python version:
from math import sin, pi
def integrate(a, b, N):
dx = (b - a)/N;
sum = 0
for i in xrange(0, N):
sum += sin(a + i*dx)
return sum*dx
print integrate(0, pi, 1000000)
And here is the timing:
2.0
real 0m1.812s
user 0m1.800s
sys 0m0.010s
Running the same program with PyPy gave:
2.0
real 0m0.386s
user 0m0.370s
sys 0m0.010s
That is a significant speedup over CPython!
Now let’s look at the Rust version (compiled with -O):
use std::f64;
fn integrate(a: f64, b: f64, n: i32) -> f64 {
let dx: f64 = (b - a)/(n as f64);
let mut sum: f64 = 0.0;
for i in 0..n {
sum += f64::sin(a + (i as f64)*dx);
}
sum * dx
}
fn main() {
let r = integrate(0.0, f64::consts::PI, 1000000);
println!("{}", r);
}
which on execution gave:
1.9999999999984077
real 0m0.224s
user 0m0.220s
sys 0m0.000s
The time varied from 0.22s to 0.28s, which is as good as that of the C code!