Skip to content

Instantly share code, notes, and snippets.

@gbausch
Last active January 28, 2021 08:16
Show Gist options
  • Save gbausch/ffc42ef994c087cecbc7bbae721bd074 to your computer and use it in GitHub Desktop.
Save gbausch/ffc42ef994c087cecbc7bbae721bd074 to your computer and use it in GitHub Desktop.
RISC-V cycle counter readout
// RISC-V cycle counter test
// Gerold Bausch, 2021
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
uint64_t get_mcycle(void) {
uint32_t mcycle, mcycleh;
// get mcycle and mcycleh
asm("csrr %0, mcycle" : "=r"(mcycle));
asm("csrr %0, mcycleh": "=r"(mcycleh));
return ((uint64_t)mcycleh << 32) | mcycle;
}
int main() {
time_t t;
srand((unsigned) time(&t));
// init variables with random numbers
int32_t a = rand()%50;
int32_t b = rand()%50;
int32_t c = 0;
uint64_t t0, t1, tdiff;
// get cycle counter
t0 = get_mcycle();
// calc some stuff
c = a + b;
printf("c: %d\n", c);
// get cycle counter
t1 = get_mcycle();
// print number of elapsed cycles
tdiff = t1-t0;
printf("Number of cycles: %d\n", tdiff);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment