- 필요 환경: - Rust 1.85+ (Edition 2024) - Python 3.12+ - maturin 1.x ## 1. 프로젝트 생성 ```shell mkdir my_rust_lib && cd my_rust_lib pip install maturin maturin init --bindings pyo3 ``` ## 2. Cargo.toml 파일 수정 ```toml [package] name = "my_rust_lib" version = "0.1.0" edition = "2024" [lib] crate-type = ["cdylib"] [dependecies] pyo3 = { version = "0.24", features = ["extension-module"] } ``` ## 3. src/lib.rs 작성 > [!WARNING] 주의 > `#[pymodule]`의 함수명은 `Cargo.toml`의 패키지명(`[package] - name`)과 일치해야 합니다. ```rust use pyo3::prelude::*; #[pyfunction] fn fibonacci(n: u64) -> u64 { match n { 0 => 0, 1 => 1, _ => fibonacci(n - 1) + fibonacci(n - 2), } } #[pyclass] struct Counter { value: i64, } #[pymethods] impl Counter { #[new] fn new(start: i64) -> Self { Counter { value: start } } fn increment(&mut self) { self.value += 1; } fn get(&self) -> i64 { self.value } } #[pymodule] fn my_rust_lib(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(fibonacci, m)?)?; m.add_class::<Counter>()?; Ok(()) } ``` ## 4. `maturin`으로 Python에서 사용할 수 있도록 만들기 ```shell # 개발 모드(현재의 Python 환경에 *직접* 설치) maturin develop # 또는 배포용 Wheel 파일 생성 # maturin build --release -o ./dist ``` ## 5. Python에서 직접 사용해보기 ```python import my_rust_lib # Rust로 작성한 모듈 # 함수 호출 print(my_rust_lib.fibonacci(10)) # 55 # 클래스 사용 counter = my_rust_lib.Counter(0) counter.increment() print(counter.get()) # 1 ``` ### 5-1. 피보나치 함수 성능 비교하기(Rust vs Python) Python 대신 Rust를 사용하는 가장 큰 이유는 바로 성능입니다. 아래의 코드를 실행하여 간단한 성능 비교를 직접 수행해보시길 바랍니다. (제 경우엔 약 15배 정도 더 빠르네요) ```python import time import my_rust_lib def fibonacci(n: int) -> int: if n < 2: return n return fibonacci(n - 1) + fibonacci(n - 2) n = 30 start = time.perf_counter() fibonacci(n) python_time = time.perf_counter() - start start = time.perf_counter() my_rust_lib.fibonacci(n) rust_time = time.perf_counter() - start print(f"Python 실행시간: {python_time:.4f}s") print(f"Rust 실행시간 : {rust_time:.4f}s") print("-------------------------") print(f"=> Rust가 {python_time / rust_time:.1f}배 더 빠르네요.") ``` --- - [[PyO3란 무엇인가]] - [[maturin은 무엇인가]]