我正在开发我的第一个 gem,称为t_time_tracker(哇哦!)。一切进展顺利;我尽可能地对其进行了优化,以尽可能少地减少执行时间:
t_time_tracker[master*]% time ruby -Ilib ./bin/t_time_tracker
You're not working on anything
0.07s user 0.03s system 67% cpu 0.141 total
(这是我的应用程序的“hello world”——不带参数调用它只会打印出“你没有在做任何事情”)
大约十分之一秒,占用了我 67% 的 CPU - 很酷,我可以忍受。感觉相当瞬间。让我们构建它:
$ gem build t_time_tracker.gemspec
$ gem install ./t_time_tracker-0.0.0.gem
并对已安装的二进制文件执行完全相同的操作:
$ time t_time_tracker
You're not working on anything
t_time_tracker 0.42s user 0.06s system 93% cpu 0.513 total
半秒?!那个是从哪里来的?!让我们添加一些调试输出并包含开发二进制文件中的系统 gem,看看瓶颈在哪里:
t_time_tracker[master*]% time ruby ./bin/t_time_tracker
(starting binary)
(require 'time' and 'optparse')
0.041432
(before `require 't_time_tracker')
0.497135
(after `require 't_time_tracker')
(Gem.loaded_specs.keys = t_time_tracker)
(initializing TTimeTracker class)
You're not working on anything
ruby ./bin/t_time_tracker 0.44s user 0.07s system 91% cpu 0.551 total
好吧,所以 `require 't_time_tracker' 行似乎是罪魁祸首。让我们在 irb 中再次尝试以进一步缩小范围:
$ irb
>> t=Time.now; require 't_time_tracker'; puts Time.now-t
0.046792
=> nil
...什么?但这只是半秒钟的时间!让我们尝试使用调试输出构建 gem:
$ gem build t_time_tracker.gemspec
$ gem install ./t_time_tracker-0.0.0.gem
$ time t_time_tracker
(starting binary) <---noticeable half second delay before this line shows up
(require 'time' and 'optparse')
0.050458
(before `require 't_time_tracker')
0.073789
(after `require 't_time_tracker')
(Gem.loaded_specs.keys = t_time_tracker)
(initializing TTimeTracker class)
You're not working on anything
t_time_tracker 0.42s user 0.06s system 88% cpu 0.546 total
所以是的,这个 0.5 秒的延迟是从哪里来的?我通常不会在意,但这是我每天要调用大约 50 次来更新我正在做的事情的事情。50 * 0.5 秒 * 365 天 * 70 年 = 失去生命的 15 天。
系统信息:
Mac OS X 10.7.3。2 GHz 英特尔酷睿 2 双核。4 GB 内存。红宝石 1.9.2p290。
% gem -v
1.8.10<---noticeable half second delay before this line shows up
% gem list | wc -l
209