gpt4 book ai didi

java - 读取/写入文件时如何克服硬件限制。

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:30:15 25 4
gpt4 key购买 nike

我最近在一次采访中被问到这个问题。

Given an input file, a regex and an output file. Read the input file, match each line to the regex and write the matching lines to an output file.

我想出了使用链接到 FileReader 的 BufferedReader 的粗略方案(以优化从磁盘读取)。我使用了类似的写作方案。

The interviewer then said that this process takes 3 seconds to read a line from the file, 1 second to compare the regex with the line and another 5 seconds to write back. so it takes a total of 9 seconds per line. How can we improve this?

我建议一次读取整个文件,处理它并一次写入整个输出文件。然而,有人告诉我这无济于事(写 1 行 = 5 秒,写 2 行 = 10 秒)。

The interviewer further said that this is due to a hardware/ hard drive limitation. I was asked how I can improve my code to reduce the total seconds (currently 9 ) per line?

我只能想到缓冲读/写,也找不到太多关于 SO 的信息。有什么想法吗 ?

最佳答案

我认为面试官正在寻找一种在写入输出的同时执行读取/正则表达式检查的解决方案。如果您设置一个通过读取和过滤异步填充的工作队列,并将写入放在单独的线程中,那么从第二行开始,合并过程每行需要五秒钟。

这里的假设是读取、解析和写入可以彼此独立发生。在这种情况下,您可以在编写第 1 行时阅读第 2 行:您只需要四秒钟来阅读和应用您的正则表达式,并且在编写者准备好第二行之前您有整整五秒钟的时间。写作仍然是你的瓶颈,但整个过程加快了大约 44%,这还不错。

关于java - 读取/写入文件时如何克服硬件限制。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15186541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com