ruby-changes:70845
From: John <ko1@a...>
Date: Thu, 13 Jan 2022 05:55:39 +0900 (JST)
Subject: [ruby-changes:70845] 2f71f6bb82 (master): Speed up and avoid kwarg hash alloc in Time.now
https://git.ruby-lang.org/ruby.git/commit/?id=2f71f6bb82 From 2f71f6bb82c561b0c0ac31b345673a6e6847efe3 Mon Sep 17 00:00:00 2001 From: John Hawthorn <john@h...> Date: Tue, 11 Jan 2022 09:10:23 -0800 Subject: Speed up and avoid kwarg hash alloc in Time.now Previously Time.now was switched to use Time.new as it added support for the in: argument. Unfortunately because Class#new is a cfunc this requires always allocating a Hash. This commit switches Time.now back to using a builtin time_s_now. This avoids the extra Hash allocation and is about 3x faster. $ benchmark-driver -e './ruby;3.1::~/.rubies/ruby-3.1.0/bin/ruby;3.0::~/.rubies/ruby-3.0.2/bin/ruby' benchmark/time_now.yml Warming up -------------------------------------- Time.now 6.704M i/s - 6.710M times in 1.000814s (149.16ns/i, 328clocks/i) Time.now(in: "+09:00") 2.003M i/s - 2.112M times in 1.054330s (499.31ns/i) Calculating ------------------------------------- ./ruby 3.1 3.0 Time.now 7.693M 2.763M 6.394M i/s - 20.113M times in 2.614428s 7.278710s 3.145572s Time.now(in: "+09:00") 2.030M 1.260M 1.617M i/s - 6.008M times in 2.960132s 4.769378s 3.716537s Comparison: Time.now ./ruby: 7693129.7 i/s 3.0: 6394109.2 i/s - 1.20x slower 3.1: 2763282.5 i/s - 2.78x slower Time.now(in: "+09:00") ./ruby: 2029757.4 i/s 3.0: 1616652.3 i/s - 1.26x slower 3.1: 1259776.2 i/s - 1.61x slower --- benchmark/time_now.yml | 3 +++ time.c | 7 +++++++ timev.rb | 2 +- 3 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 benchmark/time_now.yml diff --git a/benchmark/time_now.yml b/benchmark/time_now.yml new file mode 100644 index 00000000000..f6d6a314893 --- /dev/null +++ b/benchmark/time_now.yml @@ -0,0 +1,3 @@ https://github.com/ruby/ruby/blob/trunk/benchmark/time_now.yml#L1 +benchmark: + - 'Time.now' + - 'Time.now(in: "+09:00")' diff --git a/time.c b/time.c index 77f42fc89ab..3a004f87635 100644 --- a/time.c +++ b/time.c @@ -1931,6 +1931,13 @@ time_init_now(rb_execution_context_t *ec, VALUE time, VALUE zone) https://github.com/ruby/ruby/blob/trunk/time.c#L1931 return time; } +static VALUE +time_s_now(rb_execution_context_t *ec, VALUE klass, VALUE zone) +{ + VALUE t = time_s_alloc(klass); + return time_init_now(ec, t, zone); +} + static VALUE time_set_utc_offset(VALUE time, VALUE off) { diff --git a/timev.rb b/timev.rb index 52056f4e591..892740c5a2b 100644 --- a/timev.rb +++ b/timev.rb @@ -221,7 +221,7 @@ class Time https://github.com/ruby/ruby/blob/trunk/timev.rb#L221 # Parameter: # :include: doc/time/in.rdoc def self.now(in: nil) - new(in: Primitive.arg!(:in)) + Primitive.time_s_now(Primitive.arg!(:in)) end # _Time_ -- cgit v1.2.1 -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/