gpt4 book ai didi

ruby - 过于缓慢的 Ruby 脚本

转载 作者:太空宇宙 更新时间:2023-11-03 17:28:57 26 4
gpt4 key购买 nike

好吧,我做的第一件事是从文件中提取十六进制数,然后将它们写入 .txt(不到 1 秒),然后我传递此脚本以将它们分成 4 个十六进制数组:

txt1 = 'HEX.txt'

count = 0
File.foreach(txt1).with_index do |line|
line.each_char do |hex|
count += 1
File.open('out1.txt', 'a') do |f|
f.write(hex)
if count == 4
f.write(' ')
count = 0
end
end
end
end

但是时间太长了,十六进制的.txt只有13MB,我觉得这个脚本很糟糕,我该如何改进呢?

最佳答案

write_string = 
File.open(txt1) do |f|
f.readlines.map { |line| line.scan(/.{1,4}/) }.join(' ')
end

File.open('out1.txt', 'a') do |f|
f.write(write_string)
end

我们可以用正则表达式扫描每一行,将这行分成 4 组。然后我们只需要在 map 外加入一个连接,就可以将所有内容压缩成一个字符串,每组 4 个字符。

我认为打开和写入文件的每个字符都是速度变慢的根源。现在我们对整个文件进行一次写入。

编辑:从评论中测试了 scan 与 gsub 的想法。

file_name = 'test_file.txt'

File.open(文件名, 'a') { |f| f.puts(('a' * 200 * 1000).scan(/.{200}/)) }

给我们一个 1000 行的文件,每行 200 (50 * 4) 个字符。我在文件创建中使用了扫描,但它不是测试的一部分! :)

Benchmark.bmbm do |x| 
x.report(:scan) do
File.open(file_name) do |f|
f.readlines.map { |line| line.scan(/.{1,4}/) }.join(' ')
end
end
x.report(:gsub) do
File.open(file_name) do |f|
f.readlines.map { |line| line.gsub(/(.{4})(?=\S)/, "\\1 ") }.join(' ')
end
end
end

user system total real
scan 0.020217 0.000273 0.020490 ( 0.020522)
gsub 0.035371 0.000603 0.035974 ( 0.035975)

scan 0.020094 0.000164 0.020258 ( 0.020275)
gsub 0.034890 0.000528 0.035418 ( 0.035442)

看起来扫描速度提高了大约 43%。

关于ruby - 过于缓慢的 Ruby 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53763108/

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