标题如下。为什么润滑剂的功能要慢得多?
library(lubridate)
library(microbenchmark)
Dates <- sample(c(dates = format(seq(ISOdate(2010,1,1), by='day', length=365), format='%d-%m-%Y')), 50000, replace = TRUE)
microbenchmark(as.POSIXct(Dates, format = "%d-%b-%Y %H:%M:%S", tz = "GMT"), times = 100)
microbenchmark(dmy(Dates, tz ="GMT"), times = 100)
Unit: milliseconds
expr min lq median uq max
1 as.POSIXct(Dates, format = "%d-%b-%Y %H:%M:%S", tz = "GMT") 103.1902 104.3247 108.675 109.2632 149.871
2 dmy(Dates, tz = "GMT") 184.4871 194.1504 197.8422 214.3771 268.4911
答案 0 :(得分:42)
出于同样的原因,与riding on top of rockets相比,汽车速度较慢。增加的易用性和安全性使得汽车比火箭慢得多,但是你不太可能被炸毁,而且更容易启动,转向和制动汽车。然而,在正确的情况下(例如,我需要登月)火箭是这项工作的正确工具。现在,如果有人发明了一辆装有火箭的汽车,我们会有一些东西。
首先看看dmy
正在做什么,你会看到速度的差异(顺便提一下你的bechmarks我不会说lubridate
慢得多,因为这些是以毫秒为单位):
dmy
#在输入命令行后输入:
>dmy
function (..., quiet = FALSE, tz = "UTC")
{
dates <- unlist(list(...))
parse_date(num_to_date(dates), make_format("dmy"), quiet = quiet,
tz = tz)
}
<environment: namespace:lubridate>
我立即看到parse_date
和num_to_date
以及make_format
。让人怀疑所有这些人是什么。我们来看看:
<强> parse_date
强>
> parse_date
function (x, formats, quiet = FALSE, seps = find_separator(x),
tz = "UTC")
{
fmt <- guess_format(head(x, 100), formats, seps, quiet)
parsed <- as.POSIXct(strptime(x, fmt, tz = tz))
if (length(x) > 2 & !quiet)
message("Using date format ", fmt, ".")
failed <- sum(is.na(parsed)) - sum(is.na(x))
if (failed > 0) {
message(failed, " failed to parse.")
}
parsed
}
<environment: namespace:lubridate>
<强> num_to_date
强>
> getAnywhere(num_to_date)
A single object matching ‘num_to_date’ was found
It was found in the following places
namespace:lubridate
with value
function (x)
{
if (is.numeric(x)) {
x <- as.character(x)
x <- paste(ifelse(nchar(x)%%2 == 1, "0", ""), x, sep = "")
}
x
}
<environment: namespace:lubridate>
<强> make_format
强>
> getAnywhere(make_format)
A single object matching ‘make_format’ was found
It was found in the following places
namespace:lubridate
with value
function (order)
{
order <- strsplit(order, "")[[1]]
formats <- list(d = "%d", m = c("%m", "%b"), y = c("%y",
"%Y"))[order]
grid <- expand.grid(formats, KEEP.OUT.ATTRS = FALSE, stringsAsFactors = FALSE)
lapply(1:nrow(grid), function(i) unname(unlist(grid[i, ])))
}
<environment: namespace:lubridate>
哇我们得到了strsplit-ting
,expand-ing.grid-s
,paste-ing
,ifelse-ing
,unname-ing
等加上整个Lotta错误检查继续进行(在Zep上播放)歌曲)。所以我们这里有一些很好的语法糖。嗯好吃,但它有价格,速度。
将其与 as.POSIXct
进行比较:
getAnywhere(as.POSIXct) #tells us to use methods to see the business
methods('as.POSIXct') #tells us all the business
as.POSIXct.date #what I believe your code is using (I don't use dates though)
还有更多的内部编码和更少的错误检查as.POSIXct
所以你必须要问我是否想要轻松和安全,或者速度和力量?取决于工作。
答案 1 :(得分:10)
“Lubridate有一个内置的非常快的POSIX解析器,移植自 Simon Urbanek的快速包裹。此功能尚未实现 可选,可以使用选项激活(lubridate.fasttime = 真正)。 Lubridate将自动检测POSIX字符串并快速使用 解析器而不是默认的strptime实用程序。 “