Hmm, so it seems exprnd( ones(1,10000) ) is much faster than myexprnd( ones( 1, 10000) ), so I guess exprnd is optimized for generating many numbers at once. Fair enough.
Why are exprnd and binornd so slow?
8 views (last 30 days)
Show older comments
A couple of times I've run into the issue that the function exprnd() for generating exponential random variables is excruciatingly slow. My own function super simple function below is much faster.
function [ ret ] = myexprnd( rate )
ret = -log(rand(size(rate)))./rate;
end
The same goes for binornd. The following is much much faster:
function ret = mybinornd( n, p )
ret = sum(rand(1,n)<p);
end
Does matlab have a different set of functions for random number generation that are optimized? Why doesn't mathworks replace exprnd() and binornd() with the code above?
2 Comments
H. Birkan
on 7 Feb 2015
Edited: H. Birkan
on 7 Feb 2015
Consider the following custom code for generating matrix of binomial rnd numbers
function [ res ] = TEST_SUB_mybinornd( N, p )
[row_cnt, col_cnt] = size(N);
res = zeros(row_cnt, col_cnt);
for ii=1:row_cnt
for jj=1:col_cnt
res(ii, jj) = sum(rand(1,N(ii,jj))<p(ii,jj));
end
end
end
Even if it loops over the matrix entries when I run the following script
ns = 1000*ones(1,100000);
randprobs = rand(1,100000);
fprintf('\nStarting built-in function\n')
t=tic;
myrand = binornd(ns, randprobs);
toc(t)
fprintf('\n\nStarting TEST FUNCTION\n')
t=tic;
myrand = TEST_SUB_mybinornd( ns, randprobs );
toc(t)
I see a huge difference !!!
Starting built-in function Elapsed time is 6.246857 seconds.
Starting TEST FUNCTION Elapsed time is 2.491758 seconds.
Answers (1)
the cyclist
on 8 Jun 2012
You can directly see what MATLAB's exprnd() and binornd() functions are doing:
>> edit exprnd
>> edit binornd
The primary difference from yours is that MATLAB is doing various error-checking tasks, which could cause noticeable overhead when generating just one or a few values.
0 Comments
See Also
Categories
Find more on Random Number Generation in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!