Speed up random number generation in MATLAB

后端 未结 3 1832
离开以前
离开以前 2021-01-15 06:15

Is there any way to generate pseudo-random numbers to less precision and thus speed the process up?

Another thing is that I know it saves time if random numbers are

相关标签:
3条回答
  • 2021-01-15 06:27

    If you have a CUDA-capable GPU, you can do random number generation on it, as it's supposed to be much faster... Specifically Philox4x32-10:

    parallel.gpu.rng(0, 'Philox4x32-10');
    R = gpuArray.rand(sZ,'single'); % run this for more info: doc('gpuArray/rand')
    

    0 讨论(0)
  • 2021-01-15 06:28

    Since R2015a the rng function for configuring and seeding the global generator has a 'simdTwister' option that uses a faster "SIMD-oriented Fast Mersenne Twister" algorithm:

    rng(1,'twister');
    R = rand(1e4); % Warmup for timing
    tic
    R = rand(1e4);
    toc
    
    rng(1,'simdTwister');
    R = rand(1e4); % Warmup for timing
    tic
    R = rand(1e4);
    toc
    

    This will probably be the fastest builtin generator for your system (excepting the possibility of GPU-based generators). On my computer it's a little more than twice as fast as the default Mersenne Twister algorithm for large arrays.

    0 讨论(0)
  • 2021-01-15 06:29

    MATLAB actually implements more than one random number generator. They differ significantly in terms of execution time and in terms of "randomness" (I think, but I didn't verify). However, I understand from your question that speed is more important for you.

    % 'twister' is the default in MATLAB Versions 7.4 and later
    tic();
    for i=1:1000000
        rand('twister'); 
    end
    toc();
    %Elapsed time is 2.912960 seconds.
    
    % 'state' is the default in MATLAB versions 5 through 7.3
    tic();
    for i=1:1000000
        rand('state'); 
    end
    toc(); 
    % Elapsed time is 2.162040 seconds.
    
    % 'seed' is the default in MATLAB version 4
    tic();
    for i=1:1000000
        rand('seed'); 
    end
    toc();
    % Elapsed time is 0.758830 seconds.
    

    Important note: I ran the script above with an rather old version of MATLAB (v.7.6, a.k.a. R2008a). In newer versions, the syntax rand(generator) is discouraged . Instead, you should use the function rng(seed, generator) (online documentation). As a side effect, rng(seed, generator) gives you even more random number generators to choose from. Check the documentation for details.

    Regarding the second question: Whatever generator you pick, generating many random numbers at once will always be faster than generating many single random numbers. This is because MATLAB's internals are heavily optimized for parallel processing.

    tic();
    for i=1:100000
        rand(); 
    end
    toc();
    % Elapsed time is 0.024388 seconds.
    
    tic();
    rand(100, 1000);
    toc();
    % Elapsed time is 0.000680 seconds.
    
    0 讨论(0)
提交回复
热议问题