From a5475a460bec45e3fe368a8c31ffc6d56d3e607b Mon Sep 17 00:00:00 2001 From: Andrew Conlin Date: Tue, 17 Dec 2024 10:11:31 +0000 Subject: [PATCH] [2024-12-17] Allow for multiple timing operations - Return `Init` object from `tic`, and accept it in `toc`. This overrides the internal class time. - Return results from `toc` to remove need for class instantiation in Python. - Print elapsed time in seconds by default when `toc` is called. --- src/lib.rs | 20 +++++++++++++++----- tictoc/__init__.py | 6 +++--- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index a802ae3..00bbdf3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,6 +19,7 @@ mod tictoc { seconds: f64, } + #[derive(Clone)] #[pyclass(name = "init")] pub struct Init { time: Instant, @@ -44,23 +45,32 @@ mod tictoc { } } - fn tic(&mut self) { + fn tic(&mut self) -> PyResult { self.time = Instant::now(); self.status = true; + Ok(Init::new()) } - fn toc(&mut self) -> PyResult<()> { - if self.status == false { + fn toc(&mut self, tic: Option) -> PyResult { + let elapsed_time = match tic { + Some(ref tic) => tic.time.elapsed(), + None => self.time.elapsed(), + }; + let status = match tic { + Some(ref _tic) => true, + None => self.status, + }; + if status == false { Err(PyException::new_err("tic() must be called before toc()")) } else { - let elapsed_time = self.time.elapsed(); self.results = Results { nanos: elapsed_time.as_nanos(), micros: elapsed_time.as_micros(), millis: elapsed_time.as_millis(), seconds: elapsed_time.as_secs_f64(), }; - Ok(()) + println!("The elapsed time was {} seconds.",self.results.seconds); + Ok(self.results.clone()) } } } diff --git a/tictoc/__init__.py b/tictoc/__init__.py index 170a70b..9e15bc7 100644 --- a/tictoc/__init__.py +++ b/tictoc/__init__.py @@ -4,6 +4,6 @@ __doc__ = tictoc.__doc__ if hasattr(tictoc, "__all__"): __all__ = tictoc.__all__ -results = tictoc.init(); -tic = results.tic; -toc = results.toc; +t = tictoc.init(); +tic = t.tic; +toc = t.toc;