在Julia中更快地读取CSV文件
我注意到使用加载 CSV 文件CSV.read很慢。作为参考,我附上一个时间基准示例:
using CSV, DataFrames
file = download("https://github.com/foursquare/twofishes")
@time CSV.read(file, DataFrame)
Output:
9.450861 seconds (22.77 M allocations: 960.541 MiB, 5.48% gc time)
297 rows × 2 columns
这是一个随机数据集,与 Julia 相比,此类操作的 Python 替代品编译时间很短。既然 julia 比 python 快,为什么这个操作需要这么多时间?此外,有没有更快的替代方法来减少编译时间?
回答
您正在与运行时一起测量编译。
测量时间的一种正确方法是:
@time CSV.read(file, DataFrame)
@time CSV.read(file, DataFrame)
在第一次运行时,该函数会在第二次运行时编译,您可以使用它。
另一种选择是使用BenchmarkTools:
using BenchmarkTools
@btime CSV.read(file, DataFrame)
通常,人们使用 Julia 来处理庞大的数据集,因此单个初始编译时间并不重要。但是,可以将 CSV 和 DataFrame 编译到 Julia 的系统映像中,并且从第一次运行就可以快速执行,有关非结构的信息,请参见此处:为什么 julia 需要很长时间才能导入包? (然而这是更高级的通常不需要它)
您还有另一种选择,即降低编译器的优化级别(这适用于您的工作负载较小且经常重新启动并且您不希望图像构建带来的所有复杂性的情况。在这个笼子中,您将运行 Julia 作为:
julia --optimize=0 my_code.jl
最后,就像@Oscar Smith 在即将发布的 Julia 1.6 中提到的那样,编译时间会稍微短一些。
- I mostly disagree with this answer. For data analysis workflows this compile time matters a lot. I think a better answer would be to show 1.6 and how it decreases the time taken
- If this is a big production cluster with many short living processes I would go with building a custom Julia system image (if it is not possible to redesign the parameter sweep in such a way that a process stays alive for something like 15mins).
- Also check out https://github.com/dmolina/DaemonMode.jl