Message-ID: <87wmedh123.fsf@enricoschumann.net>
Date: 2025-01-29T19:28:36Z
From: Enrico Schumann
Subject: [R-pkg-devel] Slow down of as.POSIXct() when converting numeric data with origin specified
In-Reply-To: <CALnEB155_O+J_6hGz6y_AV-c54gX73V+pWTLMPqr6MGrR5BntQ@mail.gmail.com> (Vincent van Hees's message of "Wed, 29 Jan 2025 11:01:56 -0500")
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