以下程序将需要3.6秒的时间才能在具有2.2GHz Core 2 Duo的Macbook上运行,1.8秒可以在拥有2.53GHz Core 2 Duo的Macbook Pro上运行.这是为什么?
这有点奇怪吗?为什么当cpu的时钟速度只有15%时速度加倍?我仔细检查了cpu计数器,以确保没有2个内核在100%的使用中(以便看到cpu不忙于运行其他内容).可能是因为一个是Mac OS X Leopard,一个是Mac OS X Snow Leopard(64位)?两者都运行Ruby 1.9.2.
p RUBY_VERSION p RUBY_DESCRIPTION if defined? RUBY_DESCRIPTION n = 9_999_999 p n t = 0; 1.upto(n) {|i| t += i if i%3==0 || i%5==0}; p t
以下只是程序的输出:
在2.2GHz Core 2 Duo:(更新:Macbook标识符:MacBook3,1,因此可能是Intel Core 2 Duo(T7300 / T7500))
$time ruby 1.rb "1.9.2" "ruby 1.9.2p0 (2010-08-18 revision 29036) [i386-darwin9.8.0]" 9999999 23333331666668 real 0m3.784s user 0m3.751s sys 0m0.021s
2.53GHz Intel Core 2 Duo:(更新:Macbook标识符:MacBookPro5,4,因此可能是英特尔酷睿2双核Penryn与3 MB片上二级缓存)
$time ruby 1.rb "1.9.2" "ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-darwin10.4.0]" 9999999 23333331666668 real 0m1.893s user 0m1.809s sys 0m0.012s
测试在Windows 7上运行:
time_start = Time.now p RUBY_VERSION p RUBY_DESCRIPTION if defined? RUBY_DESCRIPTION n = 9_999_999 p n t = 0; 1.upto(n) {|i| t += i if i%3==0 || i%5==0}; p t print "Took #{Time.now - time_start} seconds to run\n"
英特尔Q6600四核2.4GHz运行Windows 7,64位:
C:\> ruby try.rb "1.9.2" "ruby 1.9.2p0 (2010-08-18) [i386-mingw32]" 9999999 23333331666668 Took 3.248186 seconds to run
英特尔920 i7 2.67GHz运行Windows 7,64位:
C:\> ruby try.rb "1.9.2" "ruby 1.9.2p0 (2010-08-18) [i386-mingw32]" 9999999 23333331666668 Took 2.044117 seconds to run
为什么i7与2.67GHz的速度比2.53GHz的Core 2 Duo要慢一些也是奇怪的.
解决方法
稍后在64位操作系统上.
引用Fixnum ruby doc:
A Fixnum holds Integer values that can
be represented in a native machine
word (minus 1 bit). If any operation
on a Fixnum exceeds this range,the
value is automatically converted to a
Bignum.
这里,本机机器字技术上是64位,但解释器编译为在32位处理器上运行.