[R-pkg-devel] Slow down of as.POSIXct() when converting numeric data with origin specified
Enrico Schumann
e@ @end|ng |rom enr|co@chum@nn@net
Wed Jan 29 20:28:36 CET 2025
On Wed, 29 Jan 2025, Vincent van Hees writes:
> Hello,
> I am trying to make the as.POSIXct() calls in my R package (GGIR) backward
> compatible with R 4.2.0 (from 2022) by always adding the origin =
> "1970-01-01" argument to the as.POSIXct() calls. However, this causes a
> substantial slow down when converting vectors of numeric time:
>
>> time = Sys.time()> time = as.numeric(seq(time, time + 500000, by = 0.01))> print(system.time(A <- as.POSIXct(time))) user system elapsed
> 0 0 0 > print(system.time(B <- as.POSIXct(time,
> origin = "1970-01-01"))) user system elapsed
> 0.153 0.326 0.505
>
>
> I am using R 4.2.2 on Ubuntu 22.04.
> In real use cases this equates to hours rather than minutes of run time.
>
> The only somewhat ugly solution I can think of is to rewrite the code as
> if-else-statement where the if-branch is run with older R versions and uses
> the origin argument, while the else-branch is run with later R versions and
> does not use the origin argument.
>
> Does anyone have a more elegant solution?
>
> Thanks, Vincent
>
You might consider using `.POSIXct`:
time <- Sys.time()
time <- as.numeric(seq(time, time + 500000, by = 0.01))
print(system.time(A <- as.POSIXct(time)))
print(system.time(B <- as.POSIXct(time, origin = "1970-01-01")))
print(system.time(C <- .POSIXct(time)))
all(A == B)
all(B == C)
--
Enrico Schumann
Lucerne, Switzerland
https://enricoschumann.net
More information about the R-package-devel
mailing list