From 64b3871822e4610a7f0eabda251cc7666db94b57 Mon Sep 17 00:00:00 2001 From: Technohacker Date: Fri, 6 Dec 2024 02:42:12 +0530 Subject: [PATCH] Fix overflow in quicktime calibration loop Fixes #529 --- src/viztracer/modules/quicktime.c | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/viztracer/modules/quicktime.c b/src/viztracer/modules/quicktime.c index 7705119a..77d60363 100644 --- a/src/viztracer/modules/quicktime.c +++ b/src/viztracer/modules/quicktime.c @@ -142,12 +142,24 @@ quicktime_init() start_ns[i] = get_system_ns(); int64_t start_after = get_system_ts(); start_ts[i] = start_before + (start_after - start_before) / 2; - t0_ts += start_ts[i]; - t0_ns += start_ns[i]; } - t0_ts /= CALIBRATE_SIZE; - t0_ns /= CALIBRATE_SIZE; + // Do the expensive average calculation outside the measurement loop + int64_t ts_remainder = 0; + int64_t ns_remainder = 0; + for (int i = 0; i < CALIBRATE_SIZE; i++) + { + // Divide by CALIBRATE_SIZE at each step instead of accumulate-and-divide to avoid overflow + t0_ts += start_ts[i] / CALIBRATE_SIZE; + t0_ns += start_ns[i] / CALIBRATE_SIZE; + + // Also accumulate the remainders, which are unlikely to overflow + ts_remainder += start_ts[i] % CALIBRATE_SIZE; + ns_remainder += start_ns[i] % CALIBRATE_SIZE; + } + // Then finally add the average remainder + t0_ts += ts_remainder / CALIBRATE_SIZE; + t0_ns += ns_remainder / CALIBRATE_SIZE; // Now let's find the base time