Skip to content

random() is very slow on Uno R4 #484

@WestfW

Description

@WestfW

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 renesas/fsp#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

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: codeRelated to content of the project itselftype: imperfectionPerceived defect in any part of project

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions