[英]How to read input line by line in Racket efficiently?
我目前使用以下方法逐行读取文件:
(for [(line (in-lines))]
但是,现在我的代码太慢了。 是否有“更快”的方式逐行读取输入?
像ramrunner一样,我怀疑问题出在其他地方。 这是我编写的一个简短程序,它生成一个10兆字节的文本文件,然后使用“在线”读取它。
#lang racket
(define chars (list->vector (string->list "abcde ")))
(define charslen (vector-length chars))
(define (random-line)
(list->string
(for/list ([i (in-range 80)])
(vector-ref chars (random charslen)))))
(define linecount (ceiling (/ (* 10 (expt 10 6)) 80)))
(time
(call-with-output-file "/tmp/sample.txt"
(λ (port)
(for ([i (in-range linecount)])
(write (random-line) port)))
#:exists 'truncate))
;; cpu time: 2512 real time: 2641 gc time: 357
;; okay, let's time reading it back in:
(time
(call-with-input-file "/tmp/sample.txt"
(λ (port)
(for ([l (in-lines port)])
'do-something))))
;; cpu time: 161 real time: 212 gc time: 26
;; cpu time: 141 real time: 143 gc time: 23
;; cpu time: 144 real time: 153 gc time: 22
(这里的时间都是毫秒)。 因此,读取10兆字节文件中的所有行需要大约六分之一秒。
这符合你所看到的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.