[英]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.