Not all RISC-V implementations enable all features by default. Some implementations disable the counters in order to conserve energy or simplify the core. This is why explicitly enabling it by the user or operating system is required.
Control and Status Registers (CSRs) are special-purpose registers used to control and monitor various aspects of the RISC-V operation. They play a critical role in managing the CPU’s state, handling exceptions, and configuring privileges.
One of the most important counting registers is mcycle. The mcycle CSR counts the number of clock cycles executed by the processor core on which the hart is running. This register is read-write. Based on mcycle, we can determine exactly how many clock cycles were spent on the instructions of interest. Additionally, the minstret CSR counts the number of instructions the hart has retired.
The counter-inhibit register mcountinhibit is a 32-bit register that controls which of the hardware performance-monitoring counters increment. If the corresponding bits are set to 1, the counters are disabled, while clearing the corresponding bits enables counting one of the counters. To enable the mcycle and minstret counter registers, the CY bit in the mcountinhibit register must be cleared.
The purpose of using mcycle is to count exactly how many clock cycles the CPU requires to execute an instruction. One approach is to read the value of mcycle before and after the desired transactions; the difference between those two values will give the number of clock cycles that have passed. Another approach is to write the value 0 in the register, then read the mcycle register at the desired moment in order to obtain the exact number of clocks that have been executed. How to use the mcycle feature is demonstrated in the example below.
In the context of RISC-V, a “hart” stands for Hardware Thread. It refers to an independent hardware execution context within a processor. Each hart is capable of executing instructions independently, and can be thought of as an individual CPU core or thread of execution.