maeshimaの日記

メモ書きです

FileUtils.cpとFile#writeどっちが速いか

require "benchmark"
require "fileutils"
file_name = "30M.txt"

open(file_name) do |src_file|
  Benchmark.bm do |x|
    x.report("cp") do
      FileUtils.cp(file_name, "30M_cp.txt")
    end
    x.report("write") do
      open("30M_write.txt", "w") do |dst_file|
        dst_file.write(src_file.read)
      end
    end
  end
end
/Users/maeshima/work/test/ruby% ruby bench_cp_and_write.rb
      user     system      total        real
cp  0.050000   0.200000   0.250000 (  0.978292)
write  0.030000   0.210000   0.240000 (  0.961145)
/Users/maeshima/work/test/ruby% ruby bench_cp_and_write.rb
      user     system      total        real
cp  0.050000   0.200000   0.250000 (  0.952396)
write  0.030000   0.210000   0.240000 (  1.005499)
/Users/maeshima/work/test/ruby% ruby bench_cp_and_write.rb
      user     system      total        real
cp  0.050000   0.200000   0.250000 (  0.798265)
write  0.020000   0.210000   0.230000 (  1.123414)
/Users/maeshima/work/test/ruby% ruby bench_cp_and_write.rb
      user     system      total        real
cp  0.050000   0.200000   0.250000 (  0.948807)
write  0.030000   0.210000   0.240000 (  1.261998)
/Users/maeshima/work/test/ruby% ruby bench_cp_and_write.rb
      user     system      total        real
cp  0.050000   0.200000   0.250000 (  0.931695)
write  0.020000   0.200000   0.220000 (  0.997353)

ベンチとってみる前はcpのほうが速いだろと思ってたけど、実際はあんまりかわらないなー。