使用time.process_time()

时间:2017-12-01 18:35:49

标签: python python-3.x attributeerror

我试图计算排序函数需要多长时间,但我正在努力让library(ggplot2) input <- as.Date("2017-09-11") # input date st <- as.Date(cut(input, "month")) # calculate start of month dates31 <- st + 0:30 # st and next 30 dates (31 in all) dates <- dates31[months(dates31) == months(st)] # keep only dates in st's month week.ch <- format(dates, "%U") # week numbers mydf <- data.frame( day = as.numeric(format(dates, "%d")), week.f = factor(week.ch, rev(unique(week.ch))), dow = factor(format(dates, "%a"), c("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")) ) ggplot(mydf, aes(x = dow, y = week.f)) + geom_tile(colour = "black", fill = "white") + geom_text(label = mydf$day, size = 4) + scale_x_discrete(expand = c(0,0)) + theme(axis.ticks = element_blank()) + theme(axis.title = element_blank()) + theme(panel.background = element_rect(fill = "transparent"))+ theme(legend.position = "none") 工作。

我目前的设置是:

time.process_time()

当我运行此操作时,我收到此错误:

  

&#39;浮动&#39;对象没有属性&#39; process_time&#39;

如何解决此问题?我想使用start = time.process_time() insertionsort(n) end = time.process_time() time = start-end

1 个答案:

答案 0 :(得分:3)

问题在于您未展示的代码的一部分。我假设您在开头导入了time模块:

import time

创建一个引用time模块的名称time

但稍后你会创建一个名为time的变量来存储时差。此时,名称time引用差异而不是模块。因此,当您尝试使用time.process_time()之后,您会收到错误。

这个简单的片段说明了问题:

>>> import time
>>> time = -(time.process_time() - time.process_time())
>>> time.process_time()
AttributeError: 'float' object has no attribute 'process_time'

如果你坚持使用time.process_time(),最好的方法是重命名存储时差的变量:

measured_execution_time_insertionsort = start - end

但您也可以直接从process_time模块导入time函数:

from time import process_time

start = process_time()
insertionsort(n)
end = process_time()

time = start - end

这两种方法都避免了名称冲突。但是,如果您想测量执行次数,我建议您使用timeit模块,它比time模块更适合此类任务。