ArduinoCore-renesas icon indicating copy to clipboard operation
ArduinoCore-renesas copied to clipboard

random() is very slow on Uno R4

Open WestfW opened this issue 5 months ago • 0 comments

The Uno R4 implementation of random() uses the Renesas RA4M true random number generator, which is part of their "security and crytography" support ("SCE"). Therefore, it needs to initialize the SCE before it can get a random number:

static long trng()
{
  uint32_t value[4];
  if (HW_SCE_McuSpecificInit() != FSP_SUCCESS)
    return -1;
  HW_SCE_RNG_Read(value);
  return (long)value[0] >= 0 ? value[0] : -value[0];
}

Unfortunately, the HW_SCE_McuSpecificInit() function is very slow (90ms), whether or not the SCE has already been initialized. (see also https://github.com/renesas/fsp/issues/413 ) If we keep track of whether the SCE is already initialized, the time use by random() goes from about 90000us to 20us:

static long trng() {
  uint32_t value[4];
  static bool SCE_inited = false;
  if (!SCE_inited) {
    if (HW_SCE_McuSpecificInit() != FSP_SUCCESS) {
      return -1;
    }
    SCE_inited = true;
  }
  HW_SCE_RNG_Read(value);
  return (long)value[0] >= 0 ? value[0] : -value[0];
}

https://forum.arduino.cc/t/random-function-on-r4-terribly-slow/1342877/12

WestfW avatar Aug 05 '25 02:08 WestfW