【发布时间】:2018-10-24 10:26:03
【问题描述】:
我有一个想要计时的函数,然后在 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)
上面的代码没有正确更新或显示正确的时差。
【问题讨论】: