News:

Masm32 SDK description, downloads and other helpful links
Message to All Guests
NB: Posting URL's See here: Posted URL Change

Main Menu

Unique seed generator for random algorithms.

Started by hutch--, August 20, 2021, 10:30:52 AM

Previous topic - Next topic

hutch--

Not every random number generator is a stellar performer and some are downright awful but there is a simple trick to get better results, simply by re-seeding the random number generator below the range where the random numbers repeat. The code is simple and easy enough to understand but you need to understand that as it is run asynchronously in its own thread, there will be a minor time lag between resuming the thread and getting the result in the GLOBAL variable rseed.

In the example below, a "waitkey$" provides that slight pause so that the thread runs to completion. It is designed to be used with a random number generator that runs long enough for the thread to run to completion and for the next re-seeding, a new seed is available without pausing the random generator.

' ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤

    #compile exe "rseed.exe"

    #include "\basic\include\win32api.inc"

    GLOBAL hThread as DWORD
    GLOBAL tID     as DWORD
    GLOBAL rseed   as DWORD
    GLOBAL sd1     as DWORD
    GLOBAL sd2     as DWORD

' ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤

FUNCTION PBmain as LONG

    hThread = CreateThread(ByVal 0,0,ByVal CodePtr(ReturnSeed),0,%CREATE_SUSPENDED,ByVal tID)

    ResumeThread hThread

    StdOut "Press any key to view result ...."+$CRLF
    waitkey$
  ' ----------------------------------
    StdOut left$(hex$(sd1),4)+" hex 1st 2 bytes"
    StdOut left$(hex$(sd2),4)+" hex 2nd 2 bytes"+$CRLF
    StdOut hex$(rseed,8)+" hex combined 4 bytes"+$CRLF
  ' ----------------------------------
    StdOut "Press any key to exit ...."+$CRLF
    waitkey$

End FUNCTION

' ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤

FUNCTION ReturnSeed(ByVal unused as DWORD) as DWORD

  lbl:
    ! cpuid
    ! rdtsc
    ! bswap eax
    ! mov sd1, eax

    ! cpuid
    ! rdtsc
    ! bswap eax
    ! mov sd2, eax

    ! mov ecx, sd1
    ! mov eax, sd2
    ! ror ecx, 16
    ! mov ax, cx

    ! mov rseed, eax

    SuspendThread GetCurrentThread
    ! jmp lbl

End FUNCTION

' ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤

Adamanteus


hutch--

Serialise instruction, forces all instructions to complete. Produces a slight delay and clears the instruction cache.

Adamanteus

Yes, unique - but in thread, could be called srand for simplify  :eusa_boohoo: