Crate function_timer
source ·Expand description
This crate allow to put a time
attribut macro on any function
or impl
block.
It will time the execution of functions and emit a histogram
metric using metrics crate.
In case the annotation is on an impl
block :
- all method will be timed
- there will be a tag
struct
with the struct name. - all
time
annotations on any method will override the one onimpl
block. - it’s possible to disable specific methods using
#[time(disable)]
.
Note that #[time(disable)]
can’t be on an impl
block.
Example
- On functions and methods :
use std::error::Error;
use metrics_exporter_prometheus::PrometheusBuilder;
use function_timer::time;
struct Test {}
impl Test {
#[time("my_metric")]
pub fn impl_function(&self) {
println!("This another test");
}
#[time("another_metric")]
pub fn impl_fail_function(&self, text:&str) -> Result<(), Box<dyn Error>>{
let number:usize = text.parse()?;
println!("{number}");
Ok(())
}
#[time("my_metric")]
pub fn static_function() {
println!("This another test");
}
}
#[time("my_metric")]
pub fn free_function() {
println!("This a test");
}
fn main() -> Result<(), Box<dyn Error>> {
let builder = PrometheusBuilder::new();
let handle = builder.install_recorder()?;
free_function();
Test::static_function();
let t = Test {};
t.impl_function();
let result = t.impl_fail_function("azerty");
assert!(result.is_err());
let result = t.impl_fail_function("1");
assert!(result.is_ok());
println!("{}", handle.render());
Ok(())
}
- on
impl
block :
use std::error::Error;
use metrics_exporter_prometheus::PrometheusBuilder;
use function_timer::time;
struct Test {}
#[time("my_metric")]
impl Test {
#[time("override_my_metric")]
pub fn impl_function(&self) {
println!("This another test");
}
pub fn impl_fail_function(&self, text:&str) -> Result<(), Box<dyn Error>>{
let number:usize = text.parse()?;
println!("{number}");
Ok(())
}
pub fn static_function() {
println!("This another test");
}
}
fn main() -> Result<(), Box<dyn Error>> {
let builder = PrometheusBuilder::new();
let handle = builder.install_recorder()?;
Test::static_function();
let t = Test {};
t.impl_function();
let result = t.impl_fail_function("azerty");
assert!(result.is_err());
let result = t.impl_fail_function("1");
assert!(result.is_ok());
println!("{}", handle.render());
Ok(())
}
Structs
- Timer.
Attribute Macros
- Macro that time a function and emit a histogram metric using
metrics
crate