9
9
"time"
10
10
11
11
"log/slog"
12
+ "math"
12
13
)
13
14
14
15
// Profile represents performance metrics for an operation
@@ -35,6 +36,26 @@ func (p *Profile) String() string {
35
36
)
36
37
}
37
38
39
+ func safeMemoryDelta (after , before uint64 ) int64 {
40
+ if after > math .MaxInt64 || before > math .MaxInt64 {
41
+ if after >= before {
42
+ diff := after - before
43
+ if diff > math .MaxInt64 {
44
+ return math .MaxInt64
45
+ }
46
+ return int64 (diff )
47
+ } else {
48
+ diff := before - after
49
+ if diff > math .MaxInt64 {
50
+ return - math .MaxInt64
51
+ }
52
+ return - int64 (diff )
53
+ }
54
+ }
55
+
56
+ return int64 (after ) - int64 (before )
57
+ }
58
+
38
59
// Profiler provides minimal performance profiling capabilities
39
60
type Profiler struct {
40
61
logger * slog.Logger
@@ -71,7 +92,7 @@ func (p *Profiler) ProfileFunc(ctx context.Context, operation string, fn func()
71
92
var memAfter runtime.MemStats
72
93
runtime .ReadMemStats (& memAfter )
73
94
profile .MemoryAfter = memAfter .Alloc
74
- profile .MemoryDelta = int64 (memAfter .Alloc ) - int64 ( memBefore .Alloc )
95
+ profile .MemoryDelta = safeMemoryDelta (memAfter .Alloc , memBefore .Alloc )
75
96
76
97
if p .logger != nil {
77
98
p .logger .InfoContext (ctx , "Performance profile" , "profile" , profile .String ())
@@ -105,7 +126,7 @@ func (p *Profiler) ProfileFuncWithMetrics(ctx context.Context, operation string,
105
126
var memAfter runtime.MemStats
106
127
runtime .ReadMemStats (& memAfter )
107
128
profile .MemoryAfter = memAfter .Alloc
108
- profile .MemoryDelta = int64 (memAfter .Alloc ) - int64 ( memBefore .Alloc )
129
+ profile .MemoryDelta = safeMemoryDelta (memAfter .Alloc , memBefore .Alloc )
109
130
110
131
if p .logger != nil {
111
132
p .logger .InfoContext (ctx , "Performance profile" , "profile" , profile .String ())
@@ -139,7 +160,7 @@ func (p *Profiler) Start(ctx context.Context, operation string) func(lines int,
139
160
var memAfter runtime.MemStats
140
161
runtime .ReadMemStats (& memAfter )
141
162
profile .MemoryAfter = memAfter .Alloc
142
- profile .MemoryDelta = int64 (memAfter .Alloc ) - int64 ( memBefore .Alloc )
163
+ profile .MemoryDelta = safeMemoryDelta (memAfter .Alloc , memBefore .Alloc )
143
164
144
165
if p .logger != nil {
145
166
p .logger .InfoContext (ctx , "Performance profile" , "profile" , profile .String ())
0 commit comments