Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

assembly - Generating random numbers using the interrupt of clock

I need to generate 5 random numbers, for that purpose i used the interrupt of clock: mov ah,2ch int 21h. I took the milliseconds(DL) and this was supposed to be the random number. But i get the same number 5 times. If you have another way to solve the problem using interrupts please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

rdrand (see comment to another answer) seems like a good idea if your processor has it. I think its pretty recent addition for Intel CPUs, so I don't think they do, and I also don't think it is very fast.

If not, and you want fast, hi-quality (psuedo) random numbers in assembly code, XORShift random number generators seem pretty good. Short code, long period, excellent statistics. Here's what I use in a (32 bit) work-stealing SMP processor scheduler to decide which processor to steal from:

DATA_ALIGN_TO_CACHE_LINE
   public XORRNGvalue32
XORRNGvalue32 dword  2463534242           ; see COMPUTE_RANDOM32 macro
; XORShift random number generator; see http://en.wikipedia.org/wiki/Xorshift
; or Marsaglia, George (July 2003). "Xorshift RNGs". Journal of Statistical Software Vol. 8 (Issue  14).

 COMPUTE_RANDOM32 macro ; uses EAX and EDX
; Marsaglia suggested 32 bit RNG:
;  unsigned long xor()
;    { static unsigned long y=2463534242; "32 bit seed value y"
;      y =(y<<13); y^=(y>>17); return (y =(y<<5)); }
      mov     eax,  XORRNGvalue32
      mov     edx, eax
      shl     eax, 13
      xor     eax, edx
      mov     edx, eax
      shr     eax, 17
      xor     eax, edx
      mov     edx, eax
      shl     eax, 5
      xor     eax, edx
      mov     XORRNGvalue32, eax ; has nice random number in EAX here
  endm

If you want to initialize the seed to a clock value (e.g., RDTSC), you can do that.

Its pretty easy to to implement a 64 bit variation; see the beautiful paper backing this up.

If you need 5 random numbers, you might do OK calling this 5 times; I'd be tempted to call it 6 times and throw one of them away. You'd be better off with 5 different routines with 5 different XOR/shift constants (Marsaglia has dozens in his paper), but if you call them all synchronously they'll all operate in lockstep. You can use your interrupt to make egregious calls to one of them to knock them out of phase.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...