[plt-scheme] interleaving the I and O in I/O

From: Prabhakar Ragde (plragde at uwaterloo.ca)
Date: Sun Jan 27 09:36:40 EST 2008

Colleagues of mine discovered this issue when automarking simple 
programs written by second-year students. Consider the following program 
for reading numbers from a file and printing the sequence out twice, 
intended to be invoked on the command line with file redirection.

(define (print-list l)
     [(null? l) (void)]
     [else (printf "~a\n" (car l))
           (print-list (cdr l))]))

(define (get-input acc)
     [(i (read))]
       [(eof-object? i) (reverse acc)]
       [else (printf "~a\n" i)
             (get-input (cons i acc))])))

(define l (get-input '()))
;(print-list l)
(print-list l)

When I save this in prog.ss on my MacBookPro running v372 and type

% time mzscheme -r prog.ss <bignums.txt >progout.txt

where bignums has 200,000 numbers, I get the following timing information:

real	0m3.775s
user	0m2.221s
sys	0m1.550s

If I comment out the (printf ...) in get-input and uncomment the 
(print-list l), the times become:

real	0m0.979s
user	0m0.915s
sys	0m0.054s

I'm curious as to what is going on and what this means for program 
design in general. Many thanks. --PR

Posted on the users mailing list.