我有一个想要计时的函数,然后在 UI 上显示执行该函数花费了多少时间。如何重新获取该函数的执行时间?我尝试将变量放在反应函数中、函数周围等。我只想计算反应函数运行所需的时间,然后显示它。我试图不使用额外的包。
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
sidebarPanel(
# User Input Text Box
textInput(inputId = "userText",
label = "",
placeholder = "Type in a partial sentence here..."),
verbatimTextOutput(outputId = "textInput", placeholder = TRUE),
# Show amount of execution time
verbatimTextOutput(outputId = "timer", placeholder = TRUE)
))
server <- function(input, output) {
# Declare Timer variables
startTime <- Sys.time()
endTime <- Sys.time()
# Some function to time: Trivial Paste Function
textToDisplay <- reactive({
req(input$userText)
startTime <- Sys.time()
textToDisplay <- paste("This is the user input text: ", input$userText)
endTime <- Sys.time()
return(textToDisplay)
})
# Display pasted text
output$textInput <- renderText({
req(input$userText)
textToDisplay()
})
# Display execution time
output$timer <- renderText({
req(input$userText)
paste0("Executed in: ",((endTime - startTime)*1000)," milliseconds")
})
}
# Run the application
shinyApp(ui = ui, server = server)
上面的代码没有正确更新或显示正确的时差。
啊,问题是startTime
and endTime
不是无功值,因此当它们改变时不会导致renderText
失效并重新运行,并且它们在反应式表达式之外无法正确保留。
只需定义一个reactiveValues
对象,并使startTime
and endTime
其中一部分。
将定义计时器变量的部分替换为:
rv <- reactiveValues()
然后,每次你打电话startTime
and endTime
, use rv$startTime
and rv$endTime
.
您仍然看不到结果,因为textToDisplay
运行速度太快,但如果您进行这些更改并添加Sys.sleep(2)
into textToDisplay
你会发现它工作正常。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)