From: Eric Hodel Date: 2005-09-10T02:41:02+09:00 Subject: Re: Optimizing a single slow method On 08 Sep 2005, at 20:46, Glenn M. Lewis wrote: > Hi! > I have a Ruby script (a small part of it is included below) > that has many methods, but one method is so incredibly slow that > I would like to write it in C++ (or any other faster language). > > The method is "Contract.parseFile(file)". I've tried the > latest SWIG, but am having a heck of a time trying to call the > two methods: "Contract.open()" and "Contract.addTick()" from within > the SWIG'd extension. (By the way, I also tried "rio(file).csv {| > fields|" > but that had the same speed as the code below.) > > Any ideas on how I can rewrite 'Contract.parseFile()' for > speed? > > Thanks! > -- Glenn Lewis > > def Contract.parseFile(file) > return unless File.exists?(file) > return if @@files.has_key?(file) > @@files[file] = 1 > print "Parsing file #{file}..." > File.open(file, "rb").each_line {|line| > line.chomp! > # puts line > fields = line.split(/,/) > next if fields.size < 8 > datestring = fields[1] > year = datestring[0..1].to_i > month = datestring[2..3].to_i > day = datestring[4..5].to_i > # puts "year=#{year}, month=#{month}, day=#{day}" > # RUBY BUG?!? Can't use 'date' here... as that messes up > findTick's 'date'... > mydate = Date.new((year < 50 ? year+2000 : year+1900), > month, day) Since Dates are created using Rational, so they can use up a significant amount of processing time. Time is much better provided your dates fit within its bounds. > contract = Contract.open(fields[0]) > tick = Tick.new(mydate, fields[2].to_f, fields[3].to_f, > fields[4].to_f, fields[5].to_f, > fields[6].to_i, fields[7].to_i) > contract.addTick(tick) > } > puts "done" > end -- Eric Hodel - drbrain@segment7.net - http://segment7.net FEC2 57F1 D465 EB15 5D6E 7C11 332A 551C 796C 9F04