Thursday, September 3, 2009

Another Random Post

Hal Pomeranz suggests this one-liner
head /dev/urandom | tr -dc 0-9 | sed -r 's/(.{8})/\1\n/g'
for generating big batches of random numbers. It's a winner: reasonable performance and easy-to-type. Timing information follows:
#!/bin/bash

echo == Shell arithmetic
(( R = 2**15-1, T = 10**8-1, C = T/R ))
readonly R T C

time for i in {0..10000}
do
printf "%8.8u\n" $(( RANDOM*C + ( RANDOM%C ) ))
done > /dev/null

echo; echo == Pipeline
time head -10000 /dev/urandom | tr -dc 0-9 | sed -r 's/(.{8})/\1\n/g' | head -10000 > /dev/null
Here's the numbers:

== Shell arithmetic

real 0m0.262s
user 0m0.256s
sys 0m0.004s

== Pipeline

real 0m0.421s
user 0m0.028s
sys 0m0.392s
Okay, the pipe's a little slower, but it's the same order of magnitude, and way easier to type.

No comments: