【问题标题】:How to read input line by line in Racket efficiently?如何有效地在 Racket 中逐行读取输入?
【发布时间】:2019-06-26 09:47:01
【问题描述】:

我目前使用以下逐行读取文件的方法:

(for [(line (in-lines))]

但是,现在我的代码太慢了。有没有“更快”的方式逐行读取输入?

【问题讨论】:

  • 你好。你能发布一些关于它有多“慢”以及你期望它是什么的信息吗?您只是加载文件还是尝试打印任何内容?因为那可能是罪魁祸首。最后,您可以使用其他一些功能来缓冲内容,而不是逐行进行。例如,您可以在内存中读取整个内容,如果它适合然后拆分它,或者按一些块大小和拆分等读取。查看this answer for ideas

标签: performance functional-programming scheme racket processing-efficiency


【解决方案1】:

和 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 兆字节文件中的所有行大约需要六分之一秒。

这与您看到的相符吗?

【讨论】:

  • 很好的例子。我将random-line 更改为(build-string 80 (λ (i) (vector-ref chars (random charslen)))) 以提高速度。
猜你喜欢
  • 2014-01-07
  • 1970-01-01
  • 2010-10-23
  • 2011-06-02
  • 2018-01-08
  • 1970-01-01
  • 1970-01-01
  • 2011-01-30
相关资源
最近更新 更多