[racket-dev] writing numbers to files is unfortunately slow

From: Matthew Flatt (mflatt at cs.utah.edu)
Date: Wed Jun 6 03:18:14 EDT 2012

The `write' function is complex in the general case to handle all sorts
of things (such as cycles or custom-write functions), but I've
streamlined the path for printing numbers so that it's a little faster
than `number->string' + `write-string'.

FWIW, you can get another 20% by lifting out the parameter lookups:

 (define (go n)
   (define p (current-output-port))
   (define r (current-pseudo-random-generator))
   (for ([i (in-range n)])
     (write (random MAXINT r) p) (newline p)))

At Tue, 5 Jun 2012 11:51:37 -0400, Sam Tobin-Hochstadt wrote:
> Having just done a pretty trivial microbenchmark of writing a lot of
> numbers to file, I discovered that Racket is sadly not as fast as one
> would hope here.  You can see the program I ran at:
> https://gist.github.com/2874695, along with a python program I
> compared it to [1].  The Racket program is about twice as slow as the
> python program:
> [samth at loki:~/tmp/dd plt] time r ints.rkt 10000000
> real	0m12.792s
> user	0m12.497s
> sys	0m0.284s
> [samth at loki:~/tmp/dd plt] time python ints.py 10000000
> real	0m7.570s
> user	0m7.188s
> sys	0m0.108s
> If we change the program to use `(write-string (number->string ...))`
> instead of `(write ...)`, things get much better:
> [samth at loki:~/tmp/dd plt] time r ints.rkt 10000000
> real	0m8.204s
> user	0m8.013s
> sys	0m0.184s
> I was surprised to see this big a change.  Is there (a) some general
> improvement lurking here, or (b) some way to get the benefit of the
> explicit conversion without writing it out?  Alternatively, should the
> Typed Racket optimizer start performing this conversion for numbers
> when printed/written?
> [1] See http://blog.cdleary.com/2012/06/simple-selfish-and-unscientific-shootout/
> for background
> -- 
> sam th
> samth at ccs.neu.edu
> _________________________
>   Racket Developers list:
>   http://lists.racket-lang.org/dev

Posted on the dev mailing list.