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.

100 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.start
  27. .to(PreciseTime::now())
  28. .num_microseconds()
  29. .unwrap(),
  30. depth: self.depth,
  31. });
  32. }
  33. }
  34. /// Timing recording
  35. #[derive(Debug, Serialize)]
  36. pub struct Timing {
  37. name: &'static str,
  38. duration: i64,
  39. depth: u32,
  40. }
  41. /// Timer tree
  42. #[derive(Debug, Serialize)]
  43. pub struct TimerTree {
  44. timings: Vec<Timing>,
  45. }
  46. impl TimerTree {
  47. /// Returns the total time elapsed in microseconds
  48. pub fn total_time(&self) -> i64 {
  49. self.timings.last().unwrap().duration
  50. }
  51. /// Open a new named subtask
  52. pub fn open(&mut self, name: &'static str) -> OpenTimer {
  53. OpenTimer {
  54. name,
  55. timer_tree: self,
  56. start: PreciseTime::now(),
  57. depth: 0,
  58. }
  59. }
  60. }
  61. impl Default for TimerTree {
  62. fn default() -> TimerTree {
  63. TimerTree {
  64. timings: Vec::new(),
  65. }
  66. }
  67. }
  68. #[cfg(test)]
  69. mod tests {
  70. use super::*;
  71. #[test]
  72. fn test_timer() {
  73. let mut timer_tree = TimerTree::default();
  74. {
  75. let mut a = timer_tree.open("a");
  76. {
  77. let mut ab = a.open("b");
  78. {
  79. let _abc = ab.open("c");
  80. }
  81. {
  82. let _abd = ab.open("d");
  83. }
  84. }
  85. }
  86. assert_eq!(timer_tree.timings.len(), 4);
  87. }
  88. }