C++ - Random seed at runtime -


how can generate different random numbers @ runtime?

i've tried

srand((unsigned) time(0)); 

but seems me random number on every startup of program, not on every execution of function itself...

i'm trying automate tests random numbers, random iterations, number of elements, etc... thought call

srand((unsigned) time(0)); 

at beginning of test function , bingo, apparently not.

what suggest me do?

srand()

as others have mentioned. srand() seeds random number generator. means sets start point sequence of random numbers. therefore in real application want call once (usually first thing in main (just after setting locale)).

int main() {     srand(time(0));      // stuff } 

now when need random number call rand().

unit tests

moving unit testing. in situation don;t want random numbers. non deterministic unit tests waste of time. if 1 fails how re-produce result can fix it?

you can still use rand() in unit tests. should initialize (with srand()) unit tests always same values when rand() called. test setup should call srand(0) before each test (or constant other 0).

the reason need call before each test, when call unit test framework run 1 test (or 1 set of tests) still use same random numbers.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -