みーのぺーじ

みーが趣味でやっているPCやソフトウェアについて.Python, Javascript, Processing, Unityなど.

RustとPythonのベンチマーク比較

計算速度が重要なソフトウェア開発のために,Rustを勉強しています.Pythonと比較し速度を体感するために,簡単にベンチマークしてみました.

環境

  • CPU 3.2GHz Core i5
  • Memory 24GBytes
  • macOS Mojave
  • rustc 1.42.0-nightly
  • Python 3.7.4 64bit

素数判定

Cargo.toml

[package]
name = "rpy"
version = "0.1.0"

[lib]
name = "rpy"
crate-type = ["cdylib"]

[dependencies.pyo3]
version = "0.8.4"
features = ["extension-module"]

src/lib.rs

use pyo3::prelude::*;
use pyo3::wrap_pyfunction;

#[pyfunction]
fn is_prime(a: i64) -> PyResult<bool> {
    if a == 1 {
        return Ok(false);
    } else if a == 2 {
        return Ok(true);
    }
    let d = (a as f64).sqrt().ceil() as i64;
    for u in 2..=d {
        if a % u == 0 {
            return Ok(false);
        }
    }
    return Ok(true);
}

#[pymodule]
fn rpy(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_wrapped(wrap_pyfunction!(is_prime))?;
    Ok(())
}

これを,cargo build --releaseする.

test.py

import math

import rpy


def isPrime(a):
    if a == 1:
        return False
    if a == 2:
        return True
    d = math.ceil(math.sqrt(a))
    for u in range(2, d+1):
        if a % u == 0:
            return False
    return True


tests = [
    (2, True),
    (3, True),
    (4, False),
    (5, True),
    (6, False),
    (10, False),
    (20, False),
    (23, True),
    (1123, True),
    (253789, True),
    (253791, False),
    (2147483647, True),
    (92709568269121, True),
    (9007199254740997, True),
    (9007199254740999, False)
]


def test_rust():
    print("[Rust]")
    for i, v in tests:
        print("{},{}".format(i, v))
        assert rpy.is_prime(i) == v, "error."


def test_python():
    print("[Python]")
    for i, v in tests:
        print("{},{}".format(i, v))
        assert isPrime(i) == v, "error."


if __name__ == '__main__':
    import timeit
    rr = timeit.repeat("test_rust()", number=1, globals=globals())
    rp = timeit.repeat("test_python()", number=1, globals=globals())
    print(min(rr), min(rp))

RustとPythonの実行時間をtimeitで計測する.

python3 test.py
>> 0.95, 10.9

Rustが約10倍早かったです.