File tree Expand file tree Collapse file tree 1 file changed +21
-1
lines changed Expand file tree Collapse file tree 1 file changed +21
-1
lines changed Original file line number Diff line number Diff line change @@ -7,12 +7,32 @@ use rand::prelude::*; // <3>
7
7
use std:: alloc:: { GlobalAlloc , System , Layout } ; // <4>
8
8
9
9
use std:: time:: Instant ; // <5>
10
+ //
11
+ use std:: cell:: Cell ;
10
12
11
13
12
14
#[ global_allocator] // <6>
13
15
static ALLOCATOR : ReportingAllocator = ReportingAllocator ;
14
16
15
17
struct ReportingAllocator ; // <7>
18
+ //
19
+ //
20
+ /// Execute a closure without logging on allocations.
21
+ pub fn run_guarded < F > ( f : F )
22
+ where
23
+ F : FnOnce ( ) ,
24
+ {
25
+ thread_local ! {
26
+ static GUARD : Cell <bool > = Cell :: new( false ) ;
27
+ }
28
+
29
+ GUARD . with ( |guard| {
30
+ if !guard. replace ( true ) {
31
+ f ( ) ;
32
+ guard. set ( false )
33
+ }
34
+ } )
35
+ }
16
36
17
37
unsafe impl GlobalAlloc for ReportingAllocator {
18
38
unsafe fn alloc ( & self , layout : Layout ) -> * mut u8 {
@@ -22,7 +42,7 @@ unsafe impl GlobalAlloc for ReportingAllocator {
22
42
let time_taken = end - start;
23
43
let bytes_requested = layout. size ( ) ;
24
44
25
- eprintln ! ( "{}\t {}" , bytes_requested, time_taken. as_nanos( ) ) ;
45
+ run_guarded ( || { eprintln ! ( "{}\t {}" , bytes_requested, time_taken. as_nanos( ) ) } ) ;
26
46
ptr
27
47
}
28
48
You can’t perform that action at this time.
0 commit comments