3

I want to create a random number in a batch file, that is not based on the system clock time.

I have been trying to use %RANDOM% but its not working well for my needs.

The reason is that I want to write file names that I'm recieving in muliple threads to files, and when I use the system time %RANDOM% method I get clashes between the files, since the system time is based on seconds and not milliseconds.

So I need a way to generate random number based on something else other than system time...

aschipfl
  • 33,626
  • 12
  • 54
  • 99
David Gidony
  • 1,243
  • 3
  • 16
  • 31
  • 3
    if you have reliable internet connection you can query random.org – npocmaka Aug 10 '16 at 10:38
  • thanks, great idea, unfortunately my system running the code is an offline server :) – David Gidony Aug 10 '16 at 11:10
  • Do you need to create a _random number_ or [unique file name](http://stackoverflow.com/q/27802376/3439404)? – JosefZ Aug 10 '16 at 15:10
  • 1
    @npocmaka, don't we have a thread on dostips about different random number algorithms. Trying to find it right now. – Squashman Aug 10 '16 at 16:44
  • [wmic os get localdatetime](http://stackoverflow.com/a/18024049/2152082) gives you a date/time string with a ms-resolution. If this is sufficcient and timing is not a problem (`wmic` is quite slow), you could use a date/time-string instead of a random number. – Stephan Oct 18 '16 at 14:46

2 Answers2

2

If you have threads, then add a random generator thread which provides random numbers to the other threads as needed. Have a single RNG running in that thread which is initialised once only from the clock. Other threads call on the random generator thread to get the next random number in the sequence.

The clock is only used once, when the random thread starts, so the problem of time clashes should not arise as long as the random thread runs for more than one second.

If necessary those other threads can use their single random number to seed their own RNGs to generate more numbers.

rossum
  • 15,344
  • 1
  • 24
  • 38
2

If the issues is that your running multiple threads, couldn't you give each batch file a 'unique ID' variable for every different thread (e.g. id) and append that to the end of %random% to generate a different number for each one. E.g:

::: Call your batch files with a unique parameter for each thread (e.g. "prog.bat 1")
set id=%%1
::: Alternatively if you're starting each thread at a different time:
:: set id=%random%

:: Later in the batch file when you're writing a file
echo %random%%id%
:: ^ a unique random number for each thread

If the multiple threads are you're only problem this should work.

Monacraft
  • 6,510
  • 2
  • 17
  • 29