最近在忙一个项目,好久没有写日志了,项目终于接近尾声,可以适当放松一下,所以记一下在这个项目中发现的有趣事情:
数组的 与 操作
- 一直以为两个数组A和B相与,谁前谁后都一样,不过这次在项目中突然想试一下,真是不试不知道一试吓一跳:
- 与 操作,长数组和短数组相与要比短数组和长数组相与更节省时间;
- 排序,对执行时间有影响,但不是特别明显。
- 代码:
#!/usr/bin/ruby
r = Random.new
radix = 10000000
vals1 = 10000000.times.collect {|i| r.rand(radix)}
vals2 = 100000.times.collect {|i| r.rand(radix)}
# 因为随机数,实际长度会小于10000000和100000
vals1_len = vals1.uniq.length
vals2_len = vals2.uniq.length
vals1_sort = vals1.sort
vals2_sort = vals2.sort
# 已排序未去重比较
stime = Time.now
vals1_sort & vals2_sort
etime = Time.now
puts ">>> sorted: #{vals1_len} & #{vals2_len} used #{etime - stime} s <<<"
stime = Time.now
vals2_sort & vals1_sort
etime = Time.now
puts ">>> sorted: #{vals2_len} & #{vals1_len} used #{etime - stime} s <<<"
# 未排序未去重比较
stime = Time.now
vals1 & vals2
etime = Time.now
puts ">>> unsort: #{vals1_len} & #{vals2_len} used #{etime - stime} s <<<"
stime = Time.now
vals2 & vals1
etime = Time.now
puts ">>> unsort: #{vals2_len} & #{vals1_len} used #{etime - stime} s <<<"
# 3次执行结果:
$ ./and_test.rb
>>> sorted: 6321701 & 99471 used 1.255142772 s <<<
>>> sorted: 99471 & 6321701 used 7.265526653 s <<<
>>> unsort: 6321701 & 99471 used 1.552287352 s <<<
>>> unsort: 99471 & 6321701 used 8.896545005 s <<<
$ ./and_test.rb
>>> sorted: 6320949 & 99497 used 1.280619044 s <<<
>>> sorted: 99497 & 6320949 used 7.423779834 s <<<
>>> unsort: 6320949 & 99497 used 1.660184257 s <<<
>>> unsort: 99497 & 6320949 used 9.337629195 s <<<
$ ./and_test.rb
>>> sorted: 6319943 & 99492 used 1.260916227 s <<<
>>> sorted: 99492 & 6319943 used 7.734610427 s <<<
>>> unsort: 6319943 & 99492 used 1.707935118 s <<<
>>> unsort: 99492 & 6319943 used 9.105055703 s <<<
未完,待续...