Need some help with how to load a python function once and use it over and over instead of loading it every time #2755
-
Hi, total noob to rust and pyo3 here. I am following the call python from rust documentation, and I have a few questions. Currently I have code like: pub fn func_py(number: usize) -> PyResult<()> {
Python::with_gil(|py| {
let start = Instant::now();
let builtins = PyModule::import(py, "builtins")?;
let sum_func = builtins.getattr("sum")?;
println!("Time taken to get function: {}", start.elapsed().as_nanos());
let start = Instant::now();
let total: i32 = sum_func.call1((vec![1, 2, number],))?.extract()?;
println!("{total}, time taken {}", start.elapsed().as_nanos());
Ok(())
})
} I notice that the time taken to get function is a lot higher compared to actually calling the function and getting the result back. Is there a way to load the function once and use it across multiple calls? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
You can convert As for using third party libraries, just do |
Beta Was this translation helpful? Give feedback.
You can convert
sum_func
to aPy<PyAny>
(just usinginto()
). That object can live outside thewith_gil
block, you can store it in a Rust struct or in alazy_static
/once_cell
global.As for using third party libraries, just do
PyModule::import(py, "pandas")
and go on from there.