How to get current system time on HiFive1 board?

Hi everyone,

I tried to use time() function to get current system time. I have included <time.h>, it can build success, but when run, it always failed. The sample code is like following:

long begin_time, end_time;

main()
{

begin_time = time ( (long *) 0);
demo_test();
end_time = time ( (long *) 0);

}

But it always fail to run, with following log in UART:

core freq at 267262361 Hz
trap

Progam has exited with code:0x0000000C

So, seems the time() function can’t be used on Hifive1 board, so how to get current system time? Thanks a lot.

mtime is a memory mapped counter defined in the RISC-V privileged specification (page 30). There are a few places in the SDK examples where you’ll see it being used a reference for a timer interrupt. For example, from the global_interrupts demo:

volatile uint64_t * mtime = (uint64_t*) (CLINT_CTRL_ADDR + CLINT_MTIME);
uint64_t now = *mtime;

Thanks dgrubb,

I have used this to get current time.

begin_time = *(volatile unsigned long *)(CLINT_CTRL_ADDR + CLINT_MTIME);
test_demo();
end_time = *(volatile unsigned long *)(CLINT_CTRL_ADDR + CLINT_MTIME);

time_cost = end_time - begin_time;

What’s the unit of this register value? Does it means the cycle it executed? So if it prints:

core freq at 263041843 Hz
Time: begin_time= 188015206, end_time= 188017751, time_cost= 2545

Whether the actual time cost is: 2545/263041843 = 9.68ms ?

Thanks in advance.

Ah, yes, I should l have mentioned that. It’s driven by the real-time clock: 32768Hz.

OK. So clock freq = 32768 Hz = 32768 cycle/s.
time_cost = 2545 cycle = 2545/32768 s = 77ms

Am I right? Thanks Dave.

It looks correct, but I don’t know whether that’s a sensible value for what’s happening inside test_demo().

One other thing: in init.c:~line 146, where the calculation for CPU frequency occurs on startup and is printed, SiFive wait until a transition on the RTC before reading a value. That makes sense for ensuring a precise measurement as the core CPU speed is far faster then the RTC so would result in better accuracy if measuring from the beginning of an RTC period rather than arbitrary point in the middle of its cycle.

Got it, I will check it and try to use CPU freq to get the time cost. Thanks~