Skip to content

Commit efe0507

Browse files
authored
ggml : fix internal overflow in ggml_time_us on Windows (#1702)
Co-authored-by: grahameth <->
1 parent e7fe66e commit efe0507

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

ggml.c

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -404,21 +404,27 @@ void ggml_fp32_to_fp16_row(const float * x, ggml_fp16_t * y, size_t n) {
404404
//
405405

406406
#if defined(_MSC_VER) || defined(__MINGW32__)
407-
static int64_t timer_freq;
407+
static int64_t timer_freq, timer_start;
408408
void ggml_time_init(void) {
409-
LARGE_INTEGER frequency;
410-
QueryPerformanceFrequency(&frequency);
411-
timer_freq = frequency.QuadPart;
409+
LARGE_INTEGER t;
410+
QueryPerformanceFrequency(&t);
411+
timer_freq = t.QuadPart;
412+
413+
// The multiplication by 1000 or 1000000 below can cause an overflow if timer_freq
414+
// and the uptime is high enough.
415+
// We subtract the program start time to reduce the likelihood of that happening.
416+
QueryPerformanceCounter(&t);
417+
timer_start = t.QuadPart;
412418
}
413419
int64_t ggml_time_ms(void) {
414420
LARGE_INTEGER t;
415421
QueryPerformanceCounter(&t);
416-
return (t.QuadPart * 1000) / timer_freq;
422+
return ((t.QuadPart-timer_start) * 1000) / timer_freq;
417423
}
418424
int64_t ggml_time_us(void) {
419425
LARGE_INTEGER t;
420426
QueryPerformanceCounter(&t);
421-
return (t.QuadPart * 1000000) / timer_freq;
427+
return ((t.QuadPart-timer_start) * 1000000) / timer_freq;
422428
}
423429
#else
424430
void ggml_time_init(void) {}

0 commit comments

Comments
 (0)