From 1759eef334df7996e339029f62b77c49e72a31d4 Mon Sep 17 00:00:00 2001 From: loikki <loic.hausammann@protonmail.ch> Date: Wed, 5 Jun 2019 18:06:07 +0200 Subject: [PATCH] Logger: Implement a binary search for the time array --- logger/logger_time.c | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/logger/logger_time.c b/logger/logger_time.c index ef5bc04451..829b87a1e1 100644 --- a/logger/logger_time.c +++ b/logger/logger_time.c @@ -224,21 +224,31 @@ size_t time_array_get_index(const struct time_array *t, const size_t offset) { #ifdef SWIFT_DEBUG_CHECKS if (!t) error("NULL pointer."); - if (offset < t->records[0].offset || offset > t->records[t->size].offset) + if (offset < t->records[0].offset || offset > t->records[t->size - 1].offset) error("Offset outside of range."); #endif - /* Find the time_array with the correct offset. */ - for (size_t i = 1; i < t->size; i++) { - if (offset < t->records[i].offset) { - return i - 1; + /* left will contain the index at the end of the loop */ + size_t left = 0; + size_t right = t->size - 1; + + /* Find the time_array with the correct offset through a bisection method. */ + while (left <= right) { + size_t center = (left + right) / 2; + const size_t offset_center = t->records[center].offset; + + if (offset > offset_center) { + left = center + 1; + } + else if (offset < offset_center) { + right = center - 1; + } + else { + return center; } - - else if (offset == t->records[i].offset) - return i; } - error("Unable to find the required offset."); + return right; } /** -- GitLab