From b28ea24963a539e6158e9ebc1e8859e35bed9a06 Mon Sep 17 00:00:00 2001 From: Michael Chirico Date: Tue, 20 Aug 2019 19:44:48 +0800 Subject: [PATCH 1/2] Closes #3158 -- simplify hour() etc for ITime --- NEWS.md | 2 ++ R/IDateTime.R | 9 ++++++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/NEWS.md b/NEWS.md index bc6b599c35..a1a19f6300 100644 --- a/NEWS.md +++ b/NEWS.md @@ -266,6 +266,8 @@ 15. `first` and `last` gain an explicit `n=1L` argument so that it's clear the default is 1, and their almost identical manual pages have been merged into one. +16. `hour()`/`minute()`/`second()` are much faster for `ITime` input, [#3518](https://github.com/Rdatatable/data.table/issues/3158). + ### Changes in [v1.12.2](https://github.com/Rdatatable/data.table/milestone/14?closed=1) (07 Apr 2019) diff --git a/R/IDateTime.R b/R/IDateTime.R index 8e03631066..1c0c725bf3 100644 --- a/R/IDateTime.R +++ b/R/IDateTime.R @@ -302,8 +302,11 @@ as.POSIXlt.ITime = function(x, ...) { # lubridate routines do not return integer values. ################################################################### +do_fastroutine = function(x) + (inherits(x, 'POSIXct') && identical(attr(x, 'tzone', exact=TRUE), 'UTC')) || + inherits(x, 'ITime') second = function(x) { - if (inherits(x, 'POSIXct') && identical(attr(x, 'tzone', exact=TRUE), 'UTC')) { + if (do_fastroutine(x)) { # if we know the object is in UTC, can calculate the hour much faster as.integer(x) %% 60L } else { @@ -311,7 +314,7 @@ second = function(x) { } } minute = function(x) { - if (inherits(x, 'POSIXct') && identical(attr(x, 'tzone', exact=TRUE), 'UTC')) { + if (do_fastroutine(x)) { # ever-so-slightly faster than x %% 3600L %/% 60L as.integer(x) %/% 60L %% 60L } else { @@ -319,7 +322,7 @@ minute = function(x) { } } hour = function(x) { - if (inherits(x, 'POSIXct') && identical(attr(x, 'tzone', exact=TRUE), 'UTC')) { + if (do_fastroutine(x)) { # ever-so-slightly faster than x %% 86400L %/% 3600L as.integer(x) %/% 3600L %% 24L } else { From e34689317f071ac9e451935acfb3ed1a32b41c08 Mon Sep 17 00:00:00 2001 From: mattdowle Date: Thu, 29 Aug 2019 19:12:45 -0700 Subject: [PATCH 2/2] coverage --- inst/tests/tests.Rraw | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/inst/tests/tests.Rraw b/inst/tests/tests.Rraw index c9067a2b42..8c72cf6c29 100644 --- a/inst/tests/tests.Rraw +++ b/inst/tests/tests.Rraw @@ -13361,6 +13361,10 @@ z = .POSIXct(3725, 'UTC') test(1962.101, second(z), 5L) test(1962.102, minute(z), 2L) test(1962.103, hour(z), 1L) +z = as.ITime(z) +test(1962.201, second(z), 5L) +test(1962.202, minute(z), 2L) +test(1962.203, hour(z), 1L) # positive and negative values for shift, #1708 DT = data.table(x = 1:10, y = 10:1)