Advertisement
Guest User

Untitled

a guest
Aug 17th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. use time::SteadyTime;
  2.  
  3. trait Stopwatch<'a> {
  4. type Guard: StopwatchGuard<'a>;
  5. fn start(&'a self) -> Self::Guard;
  6. }
  7.  
  8. trait StopwatchGuard<'a> {
  9. fn sub(&'a self, name: impl AsRef<str>) -> Self;
  10. }
  11.  
  12. struct Gauge;
  13. impl Gauge {
  14. pub fn set(&self, value: f64, name: &str) {
  15. println!("{}: {}", name, value);
  16. }
  17. }
  18.  
  19. struct MyStopwatch {
  20. gauge: Gauge,
  21. }
  22.  
  23. impl MyStopwatch {
  24. pub fn new() -> Self {
  25. Self {
  26. gauge: Gauge,
  27. }
  28. }
  29. }
  30.  
  31. struct MyStopwatchGuard<'a> {
  32. stopwatch: &'a MyStopwatch,
  33. start: SteadyTime,
  34. name: String,
  35. }
  36.  
  37. impl<'a> Drop for MyStopwatchGuard<'a> {
  38. fn drop(&mut self) {
  39. let now = SteadyTime::now();
  40. let millis = match (now - self.start).num_nanoseconds() {
  41. Some(nanos) => nanos as f64 / 1_000_000.,
  42. //None => 0., // if > 2^63 ns (292 years)
  43. None => std::i64::MAX as f64 / 1_000_000.,
  44. };
  45. self.stopwatch.gauge.set(millis, &self.name);
  46. }
  47. }
  48.  
  49. impl<'a> StopwatchGuard<'a> for MyStopwatchGuard<'a> {
  50. fn sub(&self, name: impl AsRef<str>) -> Self {
  51. MyStopwatchGuard {
  52. stopwatch: self.stopwatch,
  53. start: SteadyTime::now(),
  54. name: format!("{}.{}", self.name, name.as_ref()),
  55. }
  56. }
  57. }
  58.  
  59. impl<'a> Stopwatch<'a> for MyStopwatch {
  60. type Guard = MyStopwatchGuard<'a>;
  61. fn start(&'a self) -> Self::Guard {
  62. MyStopwatchGuard {
  63. start: SteadyTime::now(),
  64. stopwatch: self,
  65. name: "root".to_owned(),
  66. }
  67. }
  68. }
  69.  
  70. fn sleep_ms(ms: u64) {
  71. std::thread::sleep(std::time::Duration::from_millis(ms))
  72. }
  73.  
  74. fn main() {
  75.  
  76. let s = MyStopwatch::new();
  77. let foo = s.start();
  78. sleep_ms(400);
  79. {
  80. let _bar = foo.sub("bar");
  81. sleep_ms(100);
  82. }
  83. {
  84. let baz = foo.sub("baz");
  85. sleep_ms(150);
  86.  
  87. let _qux = baz.sub("qux");
  88. sleep_ms(150);
  89. }
  90.  
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement