caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
* best and fastest way to read lines from a file?
@ 2007-10-01 21:27 YC
  2007-10-01 21:55 ` [Caml-list] " Daniel Bünzli
  2007-10-01 21:55 ` Olivier Roussel
  0 siblings, 2 replies; 17+ messages in thread
From: YC @ 2007-10-01 21:27 UTC (permalink / raw)
  To: caml-list

[-- Attachment #1: Type: text/plain, Size: 1279 bytes --]

Hi all -

Newbie question: I'm wondering what's the most efficient way to read in a
file line by line?  I wrote a routine in both python and ocaml to read in a
file with 345K lines to do line count and was surprised that python's code
run roughly 3x faster.

I thought the speed should be equivalent and/or somewhat in ocaml favor,
given this is an IO-bound comparison, but perhaps Python's simplistic for
loop have a read-ahead buffer built-in, and perhaps ocaml's input channel is
unbuffered, but I'm not sure how to write a buffered code that can do a line
by line read-in.

Any insight is appreciated, thanks ;)

yc

Python code:
# test.py
#!/usr/bin/python

file = <345k-line.txt>
count = 0
for line in open (file, "r"):
    count = count + 1
print "Done: ", count

OCaml code:
(* test.ml *)
let rec line_count filename =
  let f = open_in filename in
  let rec loop file count =
    try
      ignore (input_line file);
      loop file (count + 1)
    with
      End_of_file -> count
  in
    loop f 0;;

let count = line_count <345k-line.txt> in
    Printf.printf "Done: %d" count;;

Test
$ time ./test.py
Done: 345001

real    0m0.416s
user   0m0.101s
sys    0m0.247s

$ ocamlopt -o test test.ml
$ time ./test
Done: 345001
real    0m1.483s
user   0m0.631s
sys    0m0.685s

[-- Attachment #2: Type: text/html, Size: 1844 bytes --]

^ permalink raw reply	[flat|nested] 17+ messages in thread

end of thread, other threads:[~2007-10-02 22:23 UTC | newest]

Thread overview: 17+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2007-10-01 21:27 best and fastest way to read lines from a file? YC
2007-10-01 21:55 ` [Caml-list] " Daniel Bünzli
2007-10-01 22:29   ` YC
2007-10-01 21:55 ` Olivier Roussel
2007-10-02 12:39   ` Mattias Engdegård
2007-10-02 12:56     ` Brian Hurt
2007-10-02 16:15       ` kirillkh
2007-10-02 17:10         ` verlyck, Bruno.Verlyck
2007-10-02 18:02         ` kirillkh
2007-10-02 19:35           ` skaller
2007-10-02 21:05             ` kirillkh
2007-10-02 21:07               ` Jon Harrop
2007-10-02 20:23           ` Olivier Andrieu
2007-10-02 20:49             ` kirillkh
2007-10-02 21:10               ` Jon Harrop
2007-10-02 21:15               ` David Allsopp
2007-10-02 22:23                 ` skaller

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).