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>
77use std:: alloc:: { GlobalAlloc , System , Layout } ; // <4>
88
99use std:: time:: Instant ; // <5>
10+ //
11+ use std:: cell:: Cell ;
1012
1113
1214#[ global_allocator] // <6>
1315static ALLOCATOR : ReportingAllocator = ReportingAllocator ;
1416
1517struct 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+ }
1636
1737unsafe impl GlobalAlloc for ReportingAllocator {
1838 unsafe fn alloc ( & self , layout : Layout ) -> * mut u8 {
@@ -22,7 +42,7 @@ unsafe impl GlobalAlloc for ReportingAllocator {
2242 let time_taken = end - start;
2343 let bytes_requested = layout. size ( ) ;
2444
25- eprintln ! ( "{}\t {}" , bytes_requested, time_taken. as_nanos( ) ) ;
45+ run_guarded ( || { eprintln ! ( "{}\t {}" , bytes_requested, time_taken. as_nanos( ) ) } ) ;
2646 ptr
2747 }
2848
You can’t perform that action at this time.
0 commit comments