Browse thread
best and fastest way to read lines from a file?
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Olivier Roussel <olivier.roussel@c...> |
| Subject: | Re: [Caml-list] best and fastest way to read lines from a file? |
YC a écrit :
> Hi all -
Hi!
> OCaml code:
> (* test.ml <http://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;;
The following solution is ~2.5x faster than the Python implementation on
my computer. Because there is no more exceptions in recursive calls, and
thanks to tail-recursion.
let readline f =
try Some (input_line f)
with End_of_file -> None;;
let line_count filename =
let f = open_in filename in
let rec loop count =
match (readline f) with
| Some(_) -> loop (count+1)
| None -> count in
loop 0;;
let count = line_count <345k-line.txt> in
Printf.printf "Done: %d\n" count;;
--
Olivier Roussel