Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 19 additions & 20 deletions tensorflow/lite/micro/micro_time_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -18,29 +18,28 @@ limitations under the License.
#include "tensorflow/lite/micro/testing/micro_test_v2.h"

TEST(MicroTimeTest, TestBasicTimerFunctionality) {
uint32_t ticks_per_second = tflite::ticks_per_second();

// Retry enough times to guarantee a tick advance, while not taking too long
// to complete. With 1e6 retries, assuming each loop takes tens of cycles,
// this will retry for less than 10 seconds on a 10MHz platform.
constexpr int kMaxRetries = 1e6;
unsigned int start_time = tflite::GetCurrentTimeTicks();

if (ticks_per_second != 0) {
for (int i = 0; i < kMaxRetries; i++) {
if (tflite::GetCurrentTimeTicks() - start_time > 0) {
break;
}
const uint32_t ticks_per_second = tflite::ticks_per_second();

// If the platform does not implement a timer, skip the test.
if (ticks_per_second == 0) {
return;
}

const auto start_time = tflite::GetCurrentTimeTicks();

// HARDENING: Increase retries to handle fast CPUs on platforms with low
// timer resolution (e.g., Windows ~15ms). 100 million iterations guarantees
// the loop exceeds the duration of a single tick.
constexpr int kMaxRetries = 100000000;

for (volatile int i = 0; i < kMaxRetries; i++) {
if (tflite::GetCurrentTimeTicks() != start_time) {
break;
}
}

// Ensure the timer is increasing. This works for the overflow case too, since
// (MIN_INT + x) - (MAX_INT - y) == x + y + 1. For example,
// 0x80000001(min int + 1) - 0x7FFFFFFE(max int - 1) = 0x00000003 == 3.
// GetTicksPerSecond() == 0 means the timer is not implemented on this
// platform.
EXPECT_TRUE(ticks_per_second == 0 ||
tflite::GetCurrentTimeTicks() - start_time > 0);
// Verify that time has actually advanced.
EXPECT_GT(tflite::GetCurrentTimeTicks(), start_time);
Copy link
Copy Markdown
Member

@ddavis-2015 ddavis-2015 Feb 25, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't account for hardware timer rollover. Maybe just skip this check altogether, as the for loop accounts for the hardware timer advancing?

}

TF_LITE_MICRO_TESTS_MAIN