You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.1KB

  1. use time::PreciseTime;
  2. pub struct OpenTimer<'a> {
  3. name: &'static str,
  4. timer_tree: &'a mut TimerTree,
  5. start: PreciseTime,
  6. depth: u32,
  7. }
  8. impl<'a> OpenTimer<'a> {
  9. /// Starts timing a new named subtask
  10. ///
  11. /// The timer is stopped automatically
  12. /// when the `OpenTimer` is dropped.
  13. pub fn open(&mut self, name: &'static str) -> OpenTimer {
  14. OpenTimer {
  15. name,
  16. timer_tree: self.timer_tree,
  17. start: PreciseTime::now(),
  18. depth: self.depth + 1,
  19. }
  20. }
  21. }
  22. impl<'a> Drop for OpenTimer<'a> {
  23. fn drop(&mut self) {
  24. self.timer_tree.timings.push(Timing {
  25. name: self.name,
  26. duration: self
  27. .start
  28. .to(PreciseTime::now())
  29. .num_microseconds()
  30. .unwrap(),
  31. depth: self.depth,
  32. });
  33. }
  34. }
  35. /// Timing recording
  36. #[derive(Debug, Serialize)]
  37. pub struct Timing {
  38. name: &'static str,
  39. duration: i64,
  40. depth: u32,
  41. }
  42. /// Timer tree
  43. #[derive(Debug, Serialize)]
  44. pub struct TimerTree {
  45. timings: Vec<Timing>,
  46. }
  47. impl TimerTree {
  48. /// Returns the total time elapsed in microseconds
  49. pub fn total_time(&self) -> i64 {
  50. self.timings.last().unwrap().duration
  51. }
  52. /// Open a new named subtask
  53. pub fn open(&mut self, name: &'static str) -> OpenTimer {
  54. OpenTimer {
  55. name,
  56. timer_tree: self,
  57. start: PreciseTime::now(),
  58. depth: 0,
  59. }
  60. }
  61. }
  62. impl Default for TimerTree {
  63. fn default() -> TimerTree {
  64. TimerTree {
  65. timings: Vec::new(),
  66. }
  67. }
  68. }
  69. #[cfg(test)]
  70. mod tests {
  71. use super::*;
  72. #[test]
  73. fn test_timer() {
  74. let mut timer_tree = TimerTree::default();
  75. {
  76. let mut a = timer_tree.open("a");
  77. {
  78. let mut ab = a.open("b");
  79. {
  80. let _abc = ab.open("c");
  81. }
  82. {
  83. let _abd = ab.open("d");
  84. }
  85. }
  86. }
  87. assert_eq!(timer_tree.timings.len(), 4);
  88. }
  89. }