optimize randint() function for massive performance increase
This commit is contained in:
parent
566dcc18bd
commit
b1b2d6903f
|
@ -1,6 +1,7 @@
|
|||
#ifndef RANDOM_HEADER
|
||||
#define RANDOM_HEADER
|
||||
|
||||
void random_init(void);
|
||||
size_t randint(size_t max);
|
||||
|
||||
#endif
|
||||
|
|
|
@ -25,6 +25,8 @@ main(void)
|
|||
{
|
||||
system_time = 0;
|
||||
|
||||
random_init();
|
||||
|
||||
free_pages_cnt = 0;
|
||||
busy_pages_cnt = 0;
|
||||
|
||||
|
|
34
src/random.c
34
src/random.c
|
@ -1,14 +1,34 @@
|
|||
#include <stdio.h>
|
||||
#include <fcntl.h>
|
||||
#include <stddef.h>
|
||||
#include <unistd.h>
|
||||
|
||||
size_t randint(size_t max)
|
||||
#define RANDOM_BUFFER_SIZE 16384
|
||||
|
||||
static size_t index = RANDOM_BUFFER_SIZE;
|
||||
static size_t value_buff[RANDOM_BUFFER_SIZE];
|
||||
static int random_fd = -1;
|
||||
|
||||
void
|
||||
random_init(void)
|
||||
{
|
||||
size_t random_value;
|
||||
random_fd = open("/dev/urandom", O_RDONLY);
|
||||
|
||||
int f = open("/dev/urandom", O_RDONLY);
|
||||
read(f, &random_value, 8);
|
||||
close(f);
|
||||
|
||||
return random_value % max;
|
||||
if (random_fd < 0)
|
||||
printf("[random:error] Failed to open /dev/urandom\n");
|
||||
}
|
||||
|
||||
size_t
|
||||
randint(size_t max)
|
||||
{
|
||||
if (index >= RANDOM_BUFFER_SIZE) {
|
||||
read(random_fd, value_buff, 8 * RANDOM_BUFFER_SIZE);
|
||||
|
||||
index = 0;
|
||||
}
|
||||
|
||||
size_t rv = value_buff[index] % max;
|
||||
index++;
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue