如何通过线球拍读取输入线有效?

问题描述 投票:1回答:1

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

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

然而,现在我的代码太慢。是否有一个“快”的方式逐行读取输入线?

performance functional-programming scheme racket processing-efficiency
1个回答
3
投票

像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兆字节的文件中的所有行阅读。

这是否匹配你看到什么呢?

© www.soinside.com 2019 - 2024. All rights reserved.