From: Petr Kovar Date: 2011-08-18T05:55:16+09:00 Subject: Strangely slow float to int and int to float conversion --90e6ba1efb200361af04aab9b6a2 Content-Type: text/plain; charset=ISO-8859-1 Hi, I had feeling that ruby arrays are very slow after I'd run some simple float operations on array containing only integers. But after I've writen some tests it turns out that the problem is probably in conversion int to float or float to int. Strange behaviour 1) 3_000_000 times simple int to float conversion is more then 10 times slower than float to int float to int...0.404731428s int to float...4.803439434s 30_000_000 times int to float is 100 times slower than float to int float to int...4.057228206 int to float...405.354131022 so 10 times more operations but it's 100 times slower! Strange behaviour 2) with operation multiply it flips: operation (i * 0.3452523523).to_i is 5 times slower than i * 0.3452523523 (i * 0.3452523523).to_i ... 5.187890146 i * 0.3452523523 ... 1.054155473 and with 30_000_000 cycles it's 40 times slower (i * 0.3452523523).to_i ... 413.333509812 i * 0.3452523523 ... 9.762297816 (i is integer) so there the float result conversion to int is now as slow as int to float in case 1. I'm confused about this. Could you someone explain me how the conversion works in ruby and how it is possible? The test script is attached. Thanks! -- Petr Kovar --90e6ba1efb200361af04aab9b6a2 Content-Type: application/x-ruby; name="test_float_int.rb" Content-Disposition: attachment; filename="test_float_int.rb" Content-Transfer-Encoding: base64 X-Attachment-Id: f_grgs0g790 IyEvdXNyL2Jpbi9lbnYgcnVieQoKQ09VTlQgPSAzMF8wMDBfMDAwCkNPRUYgPSAwLjM0NTI1MjM1 MjMKCmRlZiBwcm9maWxlKG1zZykKICBwcmludCAiI3ttc2d9Li4uIgogIHN0ID0gVGltZS5ub3cK ICBDT1VOVC50aW1lcyBkbyB8aXwKICAgIHlpZWxkIGkKICBlbmQKICBldCA9IFRpbWUubm93CiAg cHV0cyBldC1zdAplbmQKCiNhID0gW10KYSA9IEFycmF5Lm5ldyhDT1VOVCl7Q09VTlR9CgojcHJv ZmlsZSgiaW5pdCBhcnJheSIpIHt8aXwKIyAgYSA8PCBpCiN9Cgpwcm9maWxlKCJhIGZldGNoIGlu dCBvcCIpIHt8aXwKICBhW2ldID0gYVtpXSAvIDMKfQoKcHJvZmlsZSgiYSBpbnQgb3AiKSB7fGl8 CiAgYVtpXSA9IGkgLyAzCn0KCnByb2ZpbGUoImZsb2F0IHRvIGludCIpIHt8aXwKICBDT0VGLnRv X2kKfQoKcHJvZmlsZSgiaW50IHRvIGZsb2F0Iikge3xpfAogIGkudG9fZgp9Cgpwcm9maWxlKCJh IGZldGNoIGZsb2F0IG9wIHRvIGludCIpIHt8aXwKIyAgYVtpXSA9IChhW2ldICogQ09FRikudG9f aQogIChhW2ldICogQ09FRikudG9faQp9Cgpwcm9maWxlKCJhIGZldGNoIGZsb2F0IG9wIikge3xp fAojICBhW2ldID0gYVtpXSAqIENPRUYKICBhW2ldICogQ09FRgp9Cgpwcm9maWxlKCJhIGZsb2F0 IG9wIikge3xpfAogIGFbaV0gPSBpICogQ09FRgp9Cgo= --90e6ba1efb200361af04aab9b6a2--