1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
use crate::runtime::Handle;

cfg_unstable_metrics! {
    use std::ops::Range;
    use std::thread::ThreadId;
    cfg_64bit_metrics! {
        use std::sync::atomic::Ordering::Relaxed;
    }
    use std::time::Duration;
}

/// Handle to the runtime's metrics.
///
/// This handle is internally reference-counted and can be freely cloned. A
/// `RuntimeMetrics` handle is obtained using the [`Runtime::metrics`] method.
///
/// [`Runtime::metrics`]: crate::runtime::Runtime::metrics()
#[derive(Clone, Debug)]
pub struct RuntimeMetrics {
    handle: Handle,
}

impl RuntimeMetrics {
    pub(crate) fn new(handle: Handle) -> RuntimeMetrics {
        RuntimeMetrics { handle }
    }

    /// Returns the number of worker threads used by the runtime.
    ///
    /// The number of workers is set by configuring `worker_threads` on
    /// `runtime::Builder`. When using the `current_thread` runtime, the return
    /// value is always `1`.
    ///
    /// # Examples
    ///
    /// ```
    /// use tokio::runtime::Handle;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let metrics = Handle::current().metrics();
    ///
    ///     let n = metrics.num_workers();
    ///     println!("Runtime is using {} workers", n);
    /// }
    /// ```
    pub fn num_workers(&self) -> usize {
        self.handle.inner.num_workers()
    }

    /// Returns the current number of alive tasks in the runtime.
    ///
    /// This counter increases when a task is spawned and decreases when a
    /// task exits.
    ///
    /// # Examples
    ///
    /// ```
    /// use tokio::runtime::Handle;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let metrics = Handle::current().metrics();
    ///
    ///     let n = metrics.num_alive_tasks();
    ///     println!("Runtime has {} alive tasks", n);
    /// }
    /// ```
    pub fn num_alive_tasks(&self) -> usize {
        self.handle.inner.num_alive_tasks()
    }

    cfg_unstable_metrics! {

        /// Returns the number of additional threads spawned by the runtime.
        ///
        /// The number of workers is set by configuring `max_blocking_threads` on
        /// `runtime::Builder`.
        ///
        /// # Examples
        ///
        /// ```
        /// use tokio::runtime::Handle;
        ///
        /// #[tokio::main]
        /// async fn main() {
        ///     let _ = tokio::task::spawn_blocking(move || {
        ///         // Stand-in for compute-heavy work or using synchronous APIs
        ///         1 + 1
        ///     }).await;
        ///     let metrics = Handle::current().metrics();
        ///
        ///     let n = metrics.num_blocking_threads();
        ///     println!("Runtime has created {} threads", n);
        /// }
        /// ```
        pub fn num_blocking_threads(&self) -> usize {
            self.handle.inner.num_blocking_threads()
        }

        #[deprecated = "Renamed to num_alive_tasks"]
        /// Renamed to [`RuntimeMetrics::num_alive_tasks`]
        pub fn active_tasks_count(&self) -> usize {
            self.num_alive_tasks()
        }

        /// Returns the number of idle threads, which have spawned by the runtime
        /// for `spawn_blocking` calls.
        ///
        /// # Examples
        ///
        /// ```
        /// use tokio::runtime::Handle;
        ///
        /// #[tokio::main]
        /// async fn main() {
        ///     let _ = tokio::task::spawn_blocking(move || {
        ///         // Stand-in for compute-heavy work or using synchronous APIs
        ///         1 + 1
        ///     }).await;
        ///     let metrics = Handle::current().metrics();
        ///
        ///     let n = metrics.num_idle_blocking_threads();
        ///     println!("Runtime has {} idle blocking thread pool threads", n);
        /// }
        /// ```
        pub fn num_idle_blocking_threads(&self) -> usize {
            self.handle.inner.num_idle_blocking_threads()
        }

        /// Returns the thread id of the given worker thread.
        ///
        /// The returned value is `None` if the worker thread has not yet finished
        /// starting up.
        ///
        /// If additional information about the thread, such as its native id, are
        /// required, those can be collected in [`on_thread_start`] and correlated
        /// using the thread id.
        ///
        /// [`on_thread_start`]: crate::runtime::Builder::on_thread_start
        ///
        /// # Arguments
        ///
        /// `worker` is the index of the worker being queried. The given value must
        /// be between 0 and `num_workers()`. The index uniquely identifies a single
        /// worker and will continue to identify the worker throughout the lifetime
        /// of the runtime instance.
        ///
        /// # Panics
        ///
        /// The method panics when `worker` represents an invalid worker, i.e. is
        /// greater than or equal to `num_workers()`.
        ///
        /// # Examples
        ///
        /// ```
        /// use tokio::runtime::Handle;
        ///
        /// #[tokio::main]
        /// async fn main() {
        ///     let metrics = Handle::current().metrics();
        ///
        ///     let id = metrics.worker_thread_id(0);
        ///     println!("worker 0 has id {:?}", id);
        /// }
        /// ```
        pub fn worker_thread_id(&self, worker: usize) -> Option<ThreadId> {
            self.handle
                .inner
                .worker_metrics(worker)
                .thread_id()
        }

        cfg_64bit_metrics! {
            /// Returns the number of tasks spawned in this runtime since it was created.
            ///
            /// This count starts at zero when the runtime is created and increases by one each time a task is spawned.
            ///
            /// The counter is monotonically increasing. It is never decremented or
            /// reset to zero.
            ///
            /// # Examples
            ///
            /// ```
            /// use tokio::runtime::Handle;
            ///
            /// #[tokio::main]
            /// async fn main() {
            ///    let metrics = Handle::current().metrics();
            ///
            ///     let n = metrics.spawned_tasks_count();
            ///     println!("Runtime has had {} tasks spawned", n);
            /// }
            /// ```
            pub fn spawned_tasks_count(&self) -> u64 {
                self.handle.inner.spawned_tasks_count()
            }

            /// Returns the number of tasks scheduled from **outside** of the runtime.
            ///
            /// The remote schedule count starts at zero when the runtime is created and
            /// increases by one each time a task is woken from **outside** of the
            /// runtime. This usually means that a task is spawned or notified from a
            /// non-runtime thread and must be queued using the Runtime's injection
            /// queue, which tends to be slower.
            ///
            /// The counter is monotonically increasing. It is never decremented or
            /// reset to zero.
            ///
            /// # Examples
            ///
            /// ```
            /// use tokio::runtime::Handle;
            ///
            /// #[tokio::main]
            /// async fn main() {
            ///     let metrics = Handle::current().metrics();
            ///
            ///     let n = metrics.remote_schedule_count();
            ///     println!("{} tasks were scheduled from outside the runtime", n);
            /// }
            /// ```
            pub fn remote_schedule_count(&self) -> u64 {
                self.handle
                    .inner
                    .scheduler_metrics()
                    .remote_schedule_count
                    .load(Relaxed)
            }

            /// Returns the number of times that tasks have been forced to yield back to the scheduler
            /// after exhausting their task budgets.
            ///
            /// This count starts at zero when the runtime is created and increases by one each time a task yields due to exhausting its budget.
            ///
            /// The counter is monotonically increasing. It is never decremented or
            /// reset to zero.
            pub fn budget_forced_yield_count(&self) -> u64 {
                self.handle
                    .inner
                    .scheduler_metrics()
                    .budget_forced_yield_count
                    .load(Relaxed)
            }

            /// Returns the total number of times the given worker thread has parked.
            ///
            /// The worker park count starts at zero when the runtime is created and
            /// increases by one each time the worker parks the thread waiting for new
            /// inbound events to process. This usually means the worker has processed
            /// all pending work and is currently idle.
            ///
            /// The counter is monotonically increasing. It is never decremented or
            /// reset to zero.
            ///
            /// # Arguments
            ///
            /// `worker` is the index of the worker being queried. The given value must
            /// be between 0 and `num_workers()`. The index uniquely identifies a single
            /// worker and will continue to identify the worker throughout the lifetime
            /// of the runtime instance.
            ///
            /// # Panics
            ///
            /// The method panics when `worker` represents an invalid worker, i.e. is
            /// greater than or equal to `num_workers()`.
            ///
            /// # Examples
            ///
            /// ```
            /// use tokio::runtime::Handle;
            ///
            /// #[tokio::main]
            /// async fn main() {
            ///     let metrics = Handle::current().metrics();
            ///
            ///     let n = metrics.worker_park_count(0);
            ///     println!("worker 0 parked {} times", n);
            /// }
            /// ```
            pub fn worker_park_count(&self, worker: usize) -> u64 {
                self.handle
                    .inner
                    .worker_metrics(worker)
                    .park_count
                    .load(Relaxed)
            }

            /// Returns the total number of times the given worker thread has parked
            /// and unparked.
            ///
            /// The worker park/unpark count starts at zero when the runtime is created
            /// and increases by one each time the worker parks the thread waiting for
            /// new inbound events to process. This usually means the worker has processed
            /// all pending work and is currently idle. When new work becomes available,
            /// the worker is unparked and the park/unpark count is again increased by one.
            ///
            /// An odd count means that the worker is currently parked.
            /// An even count means that the worker is currently active.
            ///
            /// The counter is monotonically increasing. It is never decremented or
            /// reset to zero.
            ///
            /// # Arguments
            ///
            /// `worker` is the index of the worker being queried. The given value must
            /// be between 0 and `num_workers()`. The index uniquely identifies a single
            /// worker and will continue to identify the worker throughout the lifetime
            /// of the runtime instance.
            ///
            /// # Panics
            ///
            /// The method panics when `worker` represents an invalid worker, i.e. is
            /// greater than or equal to `num_workers()`.
            ///
            /// # Examples
            ///
            /// ```
            /// use tokio::runtime::Handle;
            ///
            /// #[tokio::main]
            /// async fn main() {
            ///     let metrics = Handle::current().metrics();
            ///     let n = metrics.worker_park_unpark_count(0);
            ///
            ///     println!("worker 0 parked and unparked {} times", n);
            ///
            ///     if n % 2 == 0 {
            ///         println!("worker 0 is active");
            ///     } else {
            ///         println!("worker 0 is parked");
            ///     }
            /// }
            /// ```
            pub fn worker_park_unpark_count(&self, worker: usize) -> u64 {
                self.handle
                    .inner
                    .worker_metrics(worker)
                    .park_unpark_count
                    .load(Relaxed)
            }


            /// Returns the number of times the given worker thread unparked but
            /// performed no work before parking again.
            ///
            /// The worker no-op count starts at zero when the runtime is created and
            /// increases by one each time the worker unparks the thread but finds no
            /// new work and goes back to sleep. This indicates a false-positive wake up.
            ///
            /// The counter is monotonically increasing. It is never decremented or
            /// reset to zero.
            ///
            /// # Arguments
            ///
            /// `worker` is the index of the worker being queried. The given value must
            /// be between 0 and `num_workers()`. The index uniquely identifies a single
            /// worker and will continue to identify the worker throughout the lifetime
            /// of the runtime instance.
            ///
            /// # Panics
            ///
            /// The method panics when `worker` represents an invalid worker, i.e. is
            /// greater than or equal to `num_workers()`.
            ///
            /// # Examples
            ///
            /// ```
            /// use tokio::runtime::Handle;
            ///
            /// #[tokio::main]
            /// async fn main() {
            ///     let metrics = Handle::current().metrics();
            ///
            ///     let n = metrics.worker_noop_count(0);
            ///     println!("worker 0 had {} no-op unparks", n);
            /// }
            /// ```
            pub fn worker_noop_count(&self, worker: usize) -> u64 {
                self.handle
                    .inner
                    .worker_metrics(worker)
                    .noop_count
                    .load(Relaxed)
            }

            /// Returns the number of tasks the given worker thread stole from
            /// another worker thread.
            ///
            /// This metric only applies to the **multi-threaded** runtime and will
            /// always return `0` when using the current thread runtime.
            ///
            /// The worker steal count starts at zero when the runtime is created and
            /// increases by `N` each time the worker has processed its scheduled queue
            /// and successfully steals `N` more pending tasks from another worker.
            ///
            /// The counter is monotonically increasing. It is never decremented or
            /// reset to zero.
            ///
            /// # Arguments
            ///
            /// `worker` is the index of the worker being queried. The given value must
            /// be between 0 and `num_workers()`. The index uniquely identifies a single
            /// worker and will continue to identify the worker throughout the lifetime
            /// of the runtime instance.
            ///
            /// # Panics
            ///
            /// The method panics when `worker` represents an invalid worker, i.e. is
            /// greater than or equal to `num_workers()`.
            ///
            /// # Examples
            ///
            /// ```
            /// use tokio::runtime::Handle;
            ///
            /// #[tokio::main]
            /// async fn main() {
            ///     let metrics = Handle::current().metrics();
            ///
            ///     let n = metrics.worker_steal_count(0);
            ///     println!("worker 0 has stolen {} tasks", n);
            /// }
            /// ```
            pub fn worker_steal_count(&self, worker: usize) -> u64 {
                self.handle
                    .inner
                    .worker_metrics(worker)
                    .steal_count
                    .load(Relaxed)
            }

            /// Returns the number of times the given worker thread stole tasks from
            /// another worker thread.
            ///
            /// This metric only applies to the **multi-threaded** runtime and will
            /// always return `0` when using the current thread runtime.
            ///
            /// The worker steal count starts at zero when the runtime is created and
            /// increases by one each time the worker has processed its scheduled queue
            /// and successfully steals more pending tasks from another worker.
            ///
            /// The counter is monotonically increasing. It is never decremented or
            /// reset to zero.
            ///
            /// # Arguments
            ///
            /// `worker` is the index of the worker being queried. The given value must
            /// be between 0 and `num_workers()`. The index uniquely identifies a single
            /// worker and will continue to identify the worker throughout the lifetime
            /// of the runtime instance.
            ///
            /// # Panics
            ///
            /// The method panics when `worker` represents an invalid worker, i.e. is
            /// greater than or equal to `num_workers()`.
            ///
            /// # Examples
            ///
            /// ```
            /// use tokio::runtime::Handle;
            ///
            /// #[tokio::main]
            /// async fn main() {
            ///     let metrics = Handle::current().metrics();
            ///
            ///     let n = metrics.worker_steal_operations(0);
            ///     println!("worker 0 has stolen tasks {} times", n);
            /// }
            /// ```
            pub fn worker_steal_operations(&self, worker: usize) -> u64 {
                self.handle
                    .inner
                    .worker_metrics(worker)
                    .steal_operations
                    .load(Relaxed)
            }

            /// Returns the number of tasks the given worker thread has polled.
            ///
            /// The worker poll count starts at zero when the runtime is created and
            /// increases by one each time the worker polls a scheduled task.
            ///
            /// The counter is monotonically increasing. It is never decremented or
            /// reset to zero.
            ///
            /// # Arguments
            ///
            /// `worker` is the index of the worker being queried. The given value must
            /// be between 0 and `num_workers()`. The index uniquely identifies a single
            /// worker and will continue to identify the worker throughout the lifetime
            /// of the runtime instance.
            ///
            /// # Panics
            ///
            /// The method panics when `worker` represents an invalid worker, i.e. is
            /// greater than or equal to `num_workers()`.
            ///
            /// # Examples
            ///
            /// ```
            /// use tokio::runtime::Handle;
            ///
            /// #[tokio::main]
            /// async fn main() {
            ///     let metrics = Handle::current().metrics();
            ///
            ///     let n = metrics.worker_poll_count(0);
            ///     println!("worker 0 has polled {} tasks", n);
            /// }
            /// ```
            pub fn worker_poll_count(&self, worker: usize) -> u64 {
                self.handle
                    .inner
                    .worker_metrics(worker)
                    .poll_count
                    .load(Relaxed)
            }

            /// Returns the amount of time the given worker thread has been busy.
            ///
            /// The worker busy duration starts at zero when the runtime is created and
            /// increases whenever the worker is spending time processing work. Using
            /// this value can indicate the load of the given worker. If a lot of time
            /// is spent busy, then the worker is under load and will check for inbound
            /// events less often.
            ///
            /// The timer is monotonically increasing. It is never decremented or reset
            /// to zero.
            ///
            /// # Arguments
            ///
            /// `worker` is the index of the worker being queried. The given value must
            /// be between 0 and `num_workers()`. The index uniquely identifies a single
            /// worker and will continue to identify the worker throughout the lifetime
            /// of the runtime instance.
            ///
            /// # Panics
            ///
            /// The method panics when `worker` represents an invalid worker, i.e. is
            /// greater than or equal to `num_workers()`.
            ///
            /// # Examples
            ///
            /// ```
            /// use tokio::runtime::Handle;
            ///
            /// #[tokio::main]
            /// async fn main() {
            ///     let metrics = Handle::current().metrics();
            ///
            ///     let n = metrics.worker_total_busy_duration(0);
            ///     println!("worker 0 was busy for a total of {:?}", n);
            /// }
            /// ```
            pub fn worker_total_busy_duration(&self, worker: usize) -> Duration {
                let nanos = self
                    .handle
                    .inner
                    .worker_metrics(worker)
                    .busy_duration_total
                    .load(Relaxed);
                Duration::from_nanos(nanos)
            }

            /// Returns the number of tasks scheduled from **within** the runtime on the
            /// given worker's local queue.
            ///
            /// The local schedule count starts at zero when the runtime is created and
            /// increases by one each time a task is woken from **inside** of the
            /// runtime on the given worker. This usually means that a task is spawned
            /// or notified from within a runtime thread and will be queued on the
            /// worker-local queue.
            ///
            /// The counter is monotonically increasing. It is never decremented or
            /// reset to zero.
            ///
            /// # Arguments
            ///
            /// `worker` is the index of the worker being queried. The given value must
            /// be between 0 and `num_workers()`. The index uniquely identifies a single
            /// worker and will continue to identify the worker throughout the lifetime
            /// of the runtime instance.
            ///
            /// # Panics
            ///
            /// The method panics when `worker` represents an invalid worker, i.e. is
            /// greater than or equal to `num_workers()`.
            ///
            /// # Examples
            ///
            /// ```
            /// use tokio::runtime::Handle;
            ///
            /// #[tokio::main]
            /// async fn main() {
            ///     let metrics = Handle::current().metrics();
            ///
            ///     let n = metrics.worker_local_schedule_count(0);
            ///     println!("{} tasks were scheduled on the worker's local queue", n);
            /// }
            /// ```
            pub fn worker_local_schedule_count(&self, worker: usize) -> u64 {
                self.handle
                    .inner
                    .worker_metrics(worker)
                    .local_schedule_count
                    .load(Relaxed)
            }

            /// Returns the number of times the given worker thread saturated its local
            /// queue.
            ///
            /// This metric only applies to the **multi-threaded** scheduler.
            ///
            /// The worker overflow count starts at zero when the runtime is created and
            /// increases by one each time the worker attempts to schedule a task
            /// locally, but its local queue is full. When this happens, half of the
            /// local queue is moved to the injection queue.
            ///
            /// The counter is monotonically increasing. It is never decremented or
            /// reset to zero.
            ///
            /// # Arguments
            ///
            /// `worker` is the index of the worker being queried. The given value must
            /// be between 0 and `num_workers()`. The index uniquely identifies a single
            /// worker and will continue to identify the worker throughout the lifetime
            /// of the runtime instance.
            ///
            /// # Panics
            ///
            /// The method panics when `worker` represents an invalid worker, i.e. is
            /// greater than or equal to `num_workers()`.
            ///
            /// # Examples
            ///
            /// ```
            /// use tokio::runtime::Handle;
            ///
            /// #[tokio::main]
            /// async fn main() {
            ///     let metrics = Handle::current().metrics();
            ///
            ///     let n = metrics.worker_overflow_count(0);
            ///     println!("worker 0 has overflowed its queue {} times", n);
            /// }
            /// ```
            pub fn worker_overflow_count(&self, worker: usize) -> u64 {
                self.handle
                    .inner
                    .worker_metrics(worker)
                    .overflow_count
                    .load(Relaxed)
            }
        }

        /// Returns the number of tasks currently scheduled in the runtime's
        /// injection queue.
        ///
        /// Tasks that are spawned or notified from a non-runtime thread are
        /// scheduled using the runtime's injection queue. This metric returns the
        /// **current** number of tasks pending in the injection queue. As such, the
        /// returned value may increase or decrease as new tasks are scheduled and
        /// processed.
        ///
        /// # Examples
        ///
        /// ```
        /// use tokio::runtime::Handle;
        ///
        /// #[tokio::main]
        /// async fn main() {
        ///     let metrics = Handle::current().metrics();
        ///
        ///     let n = metrics.injection_queue_depth();
        ///     println!("{} tasks currently pending in the runtime's injection queue", n);
        /// }
        /// ```
        pub fn injection_queue_depth(&self) -> usize {
            self.handle.inner.injection_queue_depth()
        }

        /// Returns the number of tasks currently scheduled in the given worker's
        /// local queue.
        ///
        /// Tasks that are spawned or notified from within a runtime thread are
        /// scheduled using that worker's local queue. This metric returns the
        /// **current** number of tasks pending in the worker's local queue. As
        /// such, the returned value may increase or decrease as new tasks are
        /// scheduled and processed.
        ///
        /// # Arguments
        ///
        /// `worker` is the index of the worker being queried. The given value must
        /// be between 0 and `num_workers()`. The index uniquely identifies a single
        /// worker and will continue to identify the worker throughout the lifetime
        /// of the runtime instance.
        ///
        /// # Panics
        ///
        /// The method panics when `worker` represents an invalid worker, i.e. is
        /// greater than or equal to `num_workers()`.
        ///
        /// # Examples
        ///
        /// ```
        /// use tokio::runtime::Handle;
        ///
        /// #[tokio::main]
        /// async fn main() {
        ///     let metrics = Handle::current().metrics();
        ///
        ///     let n = metrics.worker_local_queue_depth(0);
        ///     println!("{} tasks currently pending in worker 0's local queue", n);
        /// }
        /// ```
        pub fn worker_local_queue_depth(&self, worker: usize) -> usize {
            self.handle.inner.worker_local_queue_depth(worker)
        }

        /// Returns `true` if the runtime is tracking the distribution of task poll
        /// times.
        ///
        /// Task poll times are not instrumented by default as doing so requires
        /// calling [`Instant::now()`] twice per task poll. The feature is enabled
        /// by calling [`enable_metrics_poll_count_histogram()`] when building the
        /// runtime.
        ///
        /// # Examples
        ///
        /// ```
        /// use tokio::runtime::{self, Handle};
        ///
        /// fn main() {
        ///     runtime::Builder::new_current_thread()
        ///         .enable_metrics_poll_count_histogram()
        ///         .build()
        ///         .unwrap()
        ///         .block_on(async {
        ///             let metrics = Handle::current().metrics();
        ///             let enabled = metrics.poll_count_histogram_enabled();
        ///
        ///             println!("Tracking task poll time distribution: {:?}", enabled);
        ///         });
        /// }
        /// ```
        ///
        /// [`enable_metrics_poll_count_histogram()`]: crate::runtime::Builder::enable_metrics_poll_count_histogram
        /// [`Instant::now()`]: std::time::Instant::now
        pub fn poll_count_histogram_enabled(&self) -> bool {
            self.handle
                .inner
                .worker_metrics(0)
                .poll_count_histogram
                .is_some()
        }

        /// Returns the number of histogram buckets tracking the distribution of
        /// task poll times.
        ///
        /// This value is configured by calling
        /// [`metrics_poll_count_histogram_buckets()`] when building the runtime.
        ///
        /// # Examples
        ///
        /// ```
        /// use tokio::runtime::{self, Handle};
        ///
        /// fn main() {
        ///     runtime::Builder::new_current_thread()
        ///         .enable_metrics_poll_count_histogram()
        ///         .build()
        ///         .unwrap()
        ///         .block_on(async {
        ///             let metrics = Handle::current().metrics();
        ///             let buckets = metrics.poll_count_histogram_num_buckets();
        ///
        ///             println!("Histogram buckets: {:?}", buckets);
        ///         });
        /// }
        /// ```
        ///
        /// [`metrics_poll_count_histogram_buckets()`]:
        ///     crate::runtime::Builder::metrics_poll_count_histogram_buckets
        pub fn poll_count_histogram_num_buckets(&self) -> usize {
            self.handle
                .inner
                .worker_metrics(0)
                .poll_count_histogram
                .as_ref()
                .map(|histogram| histogram.num_buckets())
                .unwrap_or_default()
        }

        /// Returns the range of task poll times tracked by the given bucket.
        ///
        /// This value is configured by calling
        /// [`metrics_poll_count_histogram_resolution()`] when building the runtime.
        ///
        /// # Panics
        ///
        /// The method panics if `bucket` represents an invalid bucket index, i.e.
        /// is greater than or equal to `poll_count_histogram_num_buckets()`.
        ///
        /// # Examples
        ///
        /// ```
        /// use tokio::runtime::{self, Handle};
        ///
        /// fn main() {
        ///     runtime::Builder::new_current_thread()
        ///         .enable_metrics_poll_count_histogram()
        ///         .build()
        ///         .unwrap()
        ///         .block_on(async {
        ///             let metrics = Handle::current().metrics();
        ///             let buckets = metrics.poll_count_histogram_num_buckets();
        ///
        ///             for i in 0..buckets {
        ///                 let range = metrics.poll_count_histogram_bucket_range(i);
        ///                 println!("Histogram bucket {} range: {:?}", i, range);
        ///             }
        ///         });
        /// }
        /// ```
        ///
        /// [`metrics_poll_count_histogram_resolution()`]:
        ///     crate::runtime::Builder::metrics_poll_count_histogram_resolution
        #[track_caller]
        pub fn poll_count_histogram_bucket_range(&self, bucket: usize) -> Range<Duration> {
            self.handle
                .inner
                .worker_metrics(0)
                .poll_count_histogram
                .as_ref()
                .map(|histogram| {
                    let range = histogram.bucket_range(bucket);
                    std::ops::Range {
                        start: Duration::from_nanos(range.start),
                        end: Duration::from_nanos(range.end),
                    }
                })
                .unwrap_or_default()
        }

        cfg_64bit_metrics! {
            /// Returns the number of times the given worker polled tasks with a poll
            /// duration within the given bucket's range.
            ///
            /// Each worker maintains its own histogram and the counts for each bucket
            /// starts at zero when the runtime is created. Each time the worker polls a
            /// task, it tracks the duration the task poll time took and increments the
            /// associated bucket by 1.
            ///
            /// Each bucket is a monotonically increasing counter. It is never
            /// decremented or reset to zero.
            ///
            /// # Arguments
            ///
            /// `worker` is the index of the worker being queried. The given value must
            /// be between 0 and `num_workers()`. The index uniquely identifies a single
            /// worker and will continue to identify the worker throughout the lifetime
            /// of the runtime instance.
            ///
            /// `bucket` is the index of the bucket being queried. The bucket is scoped
            /// to the worker. The range represented by the bucket can be queried by
            /// calling [`poll_count_histogram_bucket_range()`]. Each worker maintains
            /// identical bucket ranges.
            ///
            /// # Panics
            ///
            /// The method panics when `worker` represents an invalid worker, i.e. is
            /// greater than or equal to `num_workers()` or if `bucket` represents an
            /// invalid bucket.
            ///
            /// # Examples
            ///
            /// ```
            /// use tokio::runtime::{self, Handle};
            ///
            /// fn main() {
            ///     runtime::Builder::new_current_thread()
            ///         .enable_metrics_poll_count_histogram()
            ///         .build()
            ///         .unwrap()
            ///         .block_on(async {
            ///             let metrics = Handle::current().metrics();
            ///             let buckets = metrics.poll_count_histogram_num_buckets();
            ///
            ///             for worker in 0..metrics.num_workers() {
            ///                 for i in 0..buckets {
            ///                     let count = metrics.poll_count_histogram_bucket_count(worker, i);
            ///                     println!("Poll count {}", count);
            ///                 }
            ///             }
            ///         });
            /// }
            /// ```
            ///
            /// [`poll_count_histogram_bucket_range()`]: crate::runtime::RuntimeMetrics::poll_count_histogram_bucket_range
            #[track_caller]
            pub fn poll_count_histogram_bucket_count(&self, worker: usize, bucket: usize) -> u64 {
                self.handle
                    .inner
                    .worker_metrics(worker)
                    .poll_count_histogram
                    .as_ref()
                    .map(|histogram| histogram.get(bucket))
                    .unwrap_or_default()
            }

            /// Returns the mean duration of task polls, in nanoseconds.
            ///
            /// This is an exponentially weighted moving average. Currently, this metric
            /// is only provided by the multi-threaded runtime.
            ///
            /// # Arguments
            ///
            /// `worker` is the index of the worker being queried. The given value must
            /// be between 0 and `num_workers()`. The index uniquely identifies a single
            /// worker and will continue to identify the worker throughout the lifetime
            /// of the runtime instance.
            ///
            /// # Panics
            ///
            /// The method panics when `worker` represents an invalid worker, i.e. is
            /// greater than or equal to `num_workers()`.
            ///
            /// # Examples
            ///
            /// ```
            /// use tokio::runtime::Handle;
            ///
            /// #[tokio::main]
            /// async fn main() {
            ///     let metrics = Handle::current().metrics();
            ///
            ///     let n = metrics.worker_mean_poll_time(0);
            ///     println!("worker 0 has a mean poll time of {:?}", n);
            /// }
            /// ```
            #[track_caller]
            pub fn worker_mean_poll_time(&self, worker: usize) -> Duration {
                let nanos = self
                    .handle
                    .inner
                    .worker_metrics(worker)
                    .mean_poll_time
                    .load(Relaxed);
                Duration::from_nanos(nanos)
            }
        }

        /// Returns the number of tasks currently scheduled in the blocking
        /// thread pool, spawned using `spawn_blocking`.
        ///
        /// This metric returns the **current** number of tasks pending in
        /// blocking thread pool. As such, the returned value may increase
        /// or decrease as new tasks are scheduled and processed.
        ///
        /// # Examples
        ///
        /// ```
        /// use tokio::runtime::Handle;
        ///
        /// #[tokio::main]
        /// async fn main() {
        ///     let metrics = Handle::current().metrics();
        ///
        ///     let n = metrics.blocking_queue_depth();
        ///     println!("{} tasks currently pending in the blocking thread pool", n);
        /// }
        /// ```
        pub fn blocking_queue_depth(&self) -> usize {
            self.handle.inner.blocking_queue_depth()
        }

        cfg_net! {
            cfg_64bit_metrics! {
                /// Returns the number of file descriptors that have been registered with the
                /// runtime's I/O driver.
                ///
                /// # Examples
                ///
                /// ```
                /// use tokio::runtime::Handle;
                ///
                /// #[tokio::main]
                /// async fn main() {
                ///     let metrics = Handle::current().metrics();
                ///
                ///     let registered_fds = metrics.io_driver_fd_registered_count();
                ///     println!("{} fds have been registered with the runtime's I/O driver.", registered_fds);
                ///
                ///     let deregistered_fds = metrics.io_driver_fd_deregistered_count();
                ///
                ///     let current_fd_count = registered_fds - deregistered_fds;
                ///     println!("{} fds are currently registered by the runtime's I/O driver.", current_fd_count);
                /// }
                /// ```
                pub fn io_driver_fd_registered_count(&self) -> u64 {
                    self.with_io_driver_metrics(|m| {
                        m.fd_registered_count.load(Relaxed)
                    })
                }

                /// Returns the number of file descriptors that have been deregistered by the
                /// runtime's I/O driver.
                ///
                /// # Examples
                ///
                /// ```
                /// use tokio::runtime::Handle;
                ///
                /// #[tokio::main]
                /// async fn main() {
                ///     let metrics = Handle::current().metrics();
                ///
                ///     let n = metrics.io_driver_fd_deregistered_count();
                ///     println!("{} fds have been deregistered by the runtime's I/O driver.", n);
                /// }
                /// ```
                pub fn io_driver_fd_deregistered_count(&self) -> u64 {
                    self.with_io_driver_metrics(|m| {
                        m.fd_deregistered_count.load(Relaxed)
                    })
                }

                /// Returns the number of ready events processed by the runtime's
                /// I/O driver.
                ///
                /// # Examples
                ///
                /// ```
                /// use tokio::runtime::Handle;
                ///
                /// #[tokio::main]
                /// async fn main() {
                ///     let metrics = Handle::current().metrics();
                ///
                ///     let n = metrics.io_driver_ready_count();
                ///     println!("{} ready events processed by the runtime's I/O driver.", n);
                /// }
                /// ```
                pub fn io_driver_ready_count(&self) -> u64 {
                    self.with_io_driver_metrics(|m| m.ready_count.load(Relaxed))
                }

                fn with_io_driver_metrics<F>(&self, f: F) -> u64
                where
                    F: Fn(&super::IoDriverMetrics) -> u64,
                {
                    // TODO: Investigate if this should return 0, most of our metrics always increase
                    // thus this breaks that guarantee.
                    self.handle
                        .inner
                        .driver()
                        .io
                        .as_ref()
                        .map(|h| f(&h.metrics))
                        .unwrap_or(0)
                }
            }
        }
    }
}