Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better performance when generating random array int[]

I am making program to campare sorting algorithms. I am using big amount of numbers. I have a performance problem in creating array full of random numbers.

Is there any way to make it faster?

Currently I am using:

int[] temp = new int[length];      
for(int i = 0; i < temp.length; i++)
{
   temp[i] = generator.nextInt(temp.length * 10);
}

where

generator = new Random();
like image 736
Gh61 Avatar asked Dec 02 '12 23:12

Gh61


1 Answers

If you want it faster, you may write your own random number generator, which is less random but faster.

Unfortunatley this is c code, but you may translate to java: Taken from http://en.wikipedia.org/wiki/Random_number_generation

For your application this will be sufficient. For crypthography not.

m_w = <choose-initializer>;    /* must not be zero */
m_z = <choose-initializer>;    /* must not be zero */

uint get_random()
{
    m_z = 36969 * (m_z & 65535) + (m_z >> 16);
    m_w = 18000 * (m_w & 65535) + (m_w >> 16);
    return (m_z << 16) + m_w;  /* 32-bit result */
}
like image 175
AlexWien Avatar answered Oct 06 '22 00:10

AlexWien