[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.
This commit is contained in:
Andrew Conlin 2024-12-17 10:11:31 +00:00
parent 3c4978bef8
commit a5475a460b
2 changed files with 18 additions and 8 deletions

View File

@ -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<Init> {
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<Init>) -> PyResult<Results> {
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())
}
}
}

View File

@ -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;