gpt4 book ai didi

r - 避免全局变量

转载 作者:行者123 更新时间:2023-12-04 11:32:54 25 4
gpt4 key购买 nike

我想制作一个基本的性能分析工具,该工具可以收集时间戳并生成带有注释的运行时间。唯一的问题是我不知道如何在不使用全局变量的情况下执行此操作。实现我要实现的功能的“正确”方法是什么?如果R已经内置了此功能,那就太好了,但是我在这里真正想找出的是如何避免使用全局变量并编写更健壮的代码。

timeStamps = c()
runTimes = list()

appendRunTimes <- function(note) {
if(length(timeStamps) < 1) {
timeStamps <<- Sys.time()
}
else {
timeStamps <<- c(timeStamps, Sys.time())
diff <- timeStamps[length(timeStamps) ] - timeStamps[length(timeStamps) - 1]
runTimes <<- c(runTimes, format(diff))
names(runTimes)[length(runTimes)] <<- note
}

}


appendRunTimes('start')
Sys.sleep(4)
appendRunTimes('test')

最佳答案

这是使用闭包重写的示例:

RTmonitor <- local({
timeStamps = c()
runTimes = list()

list(
appendRunTimes=function(note) {
if(length(timeStamps) < 1) {
timeStamps <<- Sys.time()
}
else {
timeStamps <<- c(timeStamps, Sys.time())
diff <- timeStamps[length(timeStamps) ] - timeStamps[length(timeStamps) - 1]
runTimes <<- c(runTimes, format(diff))
names(runTimes)[length(runTimes)] <<- note
}
},
viewRunTimes=function() {
return(list(timeStamps=timeStamps,runTimes=runTimes))
})
})


> RTmonitor$appendRunTimes("start")
> RTmonitor$appendRunTimes("test")
> RTmonitor$viewRunTimes()
$timeStamps
[1] "2013-01-04 18:39:12 EST" "2013-01-04 18:39:21 EST"

$runTimes
$runTimes$test
[1] "8.855587 secs"

请注意,这些值存储在闭包内部,而不是在全局环境中:
> timeStamps
Error: object 'timeStamps' not found
> runTimes
Error: object 'runTimes' not found
> RTmonitor$timeStamps
NULL
> RTmonitor$runTimes
NULL

阅读更多关于闭包和避免使用全局变量的信息:
  • Closures as solution to data merging idiom
  • How does local() differ from other approaches to closure in R?
  • Why is using `<<-` frowned upon and how can I avoid it?
  • Examples of the perils of globals in R and Stata
  • 关于r - 避免全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14166207/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com