From: William James Date: 2007-09-25T00:15:14+09:00 Subject: Re: I am new to Ruby and I could use some expert advice as to how I can make this code run faster. On Sep 24, 7:47 am, Ruby Maniac wrote: > On Sep 22, 3:16 am, William James wrote: > > > On Sep 20, 5:02 pm, Ruby Maniac wrote: > > > > I am new to Ruby and I could use some expert advice as to how I can > > > make this code run faster. > > > > def scramble(fname) > > > f = File.new(fname, "rb") > > > _fname = fname + ".scrambled" > > > begin > > > File.exist?(_fname) if File.delete(_fname) > > > rescue > > > end > > > ff = File.new(_fname, "wb+") > > > for l in f > > > l.each_byte{|c| ff.write((c | 0x80).chr) } > > > end > > > f.close() > > > ff.close() > > > end > > > If you actually want speed, use a compiled language. > > This FreeBasic code is about 160 times as fast and > > demonstrates that using Python for any reason > > whatsoever is unjustified. > > > Use Ruby when ease of programming is paramount; > > use something like FreeBasic or LuaJIT when speed > > is paramount. Never submit to Python perversion. > > > sub scramble( filename as string ) > > dim outname as string > > dim as integer in_handle, out_handle, i, size > > dim bytes(1 to 4096) as byte > > > outname = filename & ".scrambled" > > in_handle = freefile > > open filename for binary access read as in_handle > > out_handle = freefile > > open outname for binary access write as out_handle > > while not eof( in_handle ) > > size = seek( in_handle ) > > get #in_handle, , bytes() > > size = seek( in_handle ) - size > > for i = 1 to size > > bytes(i) = bytes(i) or &h80 > > next > > put #out_handle, , bytes(1), size > > wend > > close > > end sub- Hide quoted text - > > > - Show quoted text - > > Finally got this FreeBASIC code to work but it reports a runtime of 3 > seconds on a machine that reports 0.811 seconds for Python using Psyco > so this means FreeBASIC is not anywhere near as fast as Python > considering the Python code reads the whole file and then performs a > single String Translate and then write the whole file in 3 operations. The speed of the disk drive plays a large role here. Make sure that both programs are reading the file from the same drive and writing to the same drive. Also, the disk cache may have an effect. Run the FreeBasic program several times in rapid succession; you may find the first run is a lot slower than the subsequent runs. I just tried the program on a file of size 10,332,028 bytes on a 3.19GHz machine. Time: 0.1257647355875013 sec. FreeBasic isn't as fast as a top-notch C compiler, but it produces decent machine language.