高效截断 Ruby Time 对象
我试图想出一种根据给定分辨率截断 Ruby Time 对象的有效方法。
class Time
def truncate resolution
t = to_a
case resolution
when :min
t[0] = 0
when :hour
t[0] = t[1] = 0
when :day
t[0] = t[1] = 0
t[2] = 1
when :month
t[0] = t[1] = 0
t[2] = t[3] = 1
when :week
t[0] = t[1] = 0
t[2] = 1
t[3] -= t[6] - 1
when :year
t[0] = t[1] = 0
t[2] = t[3] = t[4] = 1
end
Time.local *t
end
end
有谁知道可以完成相同任务的更快版本?
I am trying to come up with an efficient method for truncating Ruby Time objects according to a given resolution.
class Time
def truncate resolution
t = to_a
case resolution
when :min
t[0] = 0
when :hour
t[0] = t[1] = 0
when :day
t[0] = t[1] = 0
t[2] = 1
when :month
t[0] = t[1] = 0
t[2] = t[3] = 1
when :week
t[0] = t[1] = 0
t[2] = 1
t[3] -= t[6] - 1
when :year
t[0] = t[1] = 0
t[2] = t[3] = t[4] = 1
end
Time.local *t
end
end
Does anyone know a faster version that achieves the same task?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
感谢你们俩。 由于我不使用 Rails,因此我复制了代码来执行性能基准测试。
结果如下:
看起来我的第一个截断版本仍然是最有效的,除了年份情况。 不过,今年
truncate
和truncate3
有一个小怪癖。 它显示为而不是
任何想法为什么?
Thanks to both of you. Since I don't use Rails I copied the code to perform a performance benchmark.
Here are the results:
Seems like my first truncation version is still most efficient, except for the year case. There is a small quirk in the year for
truncate
andtruncate3
though. It is displayed asrather than
Any ideas why?
如果你不想像格雷格建议的那样使用 ActiveSupport,我想你可以做这样的事情,
但不知道它是否更快......
If you don't want ActiveSupport as Greg suggests, I think you could do something like this
Don't know if it's faster though...
您不必使用 Rails 即可使用 ActiveSupport 功能。 除了想要使用 1.day 或 3.mines 或 Time.now.beginning__of__day 之类的东西之外,我还遇到了这个确切的问题
You don't have to use Rails to use the ActiveSupport goodies. I ran into this exact problem in addition to wanting to use stuff like 1.day or 3.minutes or Time.now.beginning__of__day
这已经在 Rails 的 ActiveSupport 库的 时间扩展。 请参阅
change
方法以及各种at_beginning_of_*
方法。This has already been implemented for you in Rails' ActiveSupport library's Time extensions. See the
change
method, as well as the variousat_beginning_of_*
methods.