Skip to content

add timing functions #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
63 changes: 63 additions & 0 deletions src/main.c
Original file line number Diff line number Diff line change
@@ -5,6 +5,7 @@
*/

#include <zephyr.h>
#include <kernel.h>
#include <console/console.h>
#include <sys/printk.h>
#include <tvm/runtime/micro/micro_rpc_server.h>
@@ -20,6 +21,68 @@ void TVMPlatformAbort(int error) {
for (;;) ;
}

u32_t g_utvm_start_time;

#define MILLIS_TIL_EXPIRY 200
#define TIME_TIL_EXPIRY (K_MSEC(MILLIS_TIL_EXPIRY))
K_TIMER_DEFINE(g_utvm_timer, /* expiry func */ NULL, /* stop func */ NULL);

int g_utvm_timer_running = 0;

int TVMPlatformTimerStart() {
if (g_utvm_timer_running) {
TVMLogf("timer already running");
return -1;
}
k_timer_start(&g_utvm_timer, TIME_TIL_EXPIRY, TIME_TIL_EXPIRY);
g_utvm_start_time = k_cycle_get_32();
g_utvm_timer_running = 1;
return 0;
}

int TVMPlatformTimerStop(double* res_us) {
if (!g_utvm_timer_running) {
TVMLogf("timer not running");
return -1;
}

u32_t stop_time = k_cycle_get_32();

// compute how long the work took
u32_t cycles_spent = stop_time - g_utvm_start_time;
if (stop_time < g_utvm_start_time) {
// we rolled over *at least* once, so correct the rollover it was *only*
// once, because we might still use this result
cycles_spent = ~((u32_t) 0) - (g_utvm_start_time - stop_time);
}

u32_t ns_spent = (u32_t) k_cyc_to_ns_floor64(cycles_spent);
double hw_clock_res_us = ns_spent / 1000.0;

// need to grab time remaining *before* stopping. when stopped, this function
// always returns 0.
s32_t time_remaining_ms = k_timer_remaining_get(&g_utvm_timer);
k_timer_stop(&g_utvm_timer);
// check *after* stopping to prevent extra expiries on the happy path
if (time_remaining_ms < 0) {
TVMLogf("negative time remaining");
return -1;
}
u32_t num_expiries = k_timer_status_get(&g_utvm_timer);
u32_t timer_res_ms = ((num_expiries * MILLIS_TIL_EXPIRY) + time_remaining_ms);
double approx_num_cycles = (double) k_ticks_to_cyc_floor32(1) * (double) k_ms_to_ticks_ceil32(timer_res_ms);
// if we approach the limits of the HW clock datatype (u32_t), use the
// coarse-grained timer result instead
if (approx_num_cycles > (0.5 * (~((u32_t) 0)))) {
*res_us = timer_res_ms * 1000.0;
} else {
*res_us = hw_clock_res_us;
}

g_utvm_timer_running = 0;
return 0;
}

#define WORKSPACE_SIZE_BYTES (120 * 1024)
#define WORKSPACE_PAGE_SIZE_BYTES_LOG2 8