'How to use risc-v timer for accurate timing generation

This question is regarding the machine timer of risc-v. I'd like to use the timer to generate an accurate frequency interrupt. My timer clock runs at 50MHz and I'd like to get an interrupt every 1ms.

I therefore set the mtimecmp = 50000;. As soon as mtime >= mtimecmp there's going to be an interrupt, according to the risc-v specification.

In my interrupt handler I do this: mtime -= 50000;

This should prime the timer for the next interrupt at precisely 1kHz. The problem I'm facing is that the execution of above statement does require more than 0 clocks, which means the mtime register is set to a value a little bit too low, leading to an average interrupt frequency of slightly less than 1kHz. I'm wondering if there's a solution to this. Is it possible to get an accurate interrupt frequency using the stock risc-v mtimer? How?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source