99 "time"
1010
1111 "log/slog"
12+ "math"
1213)
1314
1415// Profile represents performance metrics for an operation
@@ -35,6 +36,26 @@ func (p *Profile) String() string {
3536 )
3637}
3738
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+
3859// Profiler provides minimal performance profiling capabilities
3960type Profiler struct {
4061 logger * slog.Logger
@@ -71,7 +92,7 @@ func (p *Profiler) ProfileFunc(ctx context.Context, operation string, fn func()
7192 var memAfter runtime.MemStats
7293 runtime .ReadMemStats (& memAfter )
7394 profile .MemoryAfter = memAfter .Alloc
74- profile .MemoryDelta = int64 (memAfter .Alloc ) - int64 ( memBefore .Alloc )
95+ profile .MemoryDelta = safeMemoryDelta (memAfter .Alloc , memBefore .Alloc )
7596
7697 if p .logger != nil {
7798 p .logger .InfoContext (ctx , "Performance profile" , "profile" , profile .String ())
@@ -105,7 +126,7 @@ func (p *Profiler) ProfileFuncWithMetrics(ctx context.Context, operation string,
105126 var memAfter runtime.MemStats
106127 runtime .ReadMemStats (& memAfter )
107128 profile .MemoryAfter = memAfter .Alloc
108- profile .MemoryDelta = int64 (memAfter .Alloc ) - int64 ( memBefore .Alloc )
129+ profile .MemoryDelta = safeMemoryDelta (memAfter .Alloc , memBefore .Alloc )
109130
110131 if p .logger != nil {
111132 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,
139160 var memAfter runtime.MemStats
140161 runtime .ReadMemStats (& memAfter )
141162 profile .MemoryAfter = memAfter .Alloc
142- profile .MemoryDelta = int64 (memAfter .Alloc ) - int64 ( memBefore .Alloc )
163+ profile .MemoryDelta = safeMemoryDelta (memAfter .Alloc , memBefore .Alloc )
143164
144165 if p .logger != nil {
145166 p .logger .InfoContext (ctx , "Performance profile" , "profile" , profile .String ())
0 commit comments