如何在R中基于system.time用户时间绘制三个函数的运行时间曲线?
Got it, let's walk through how to do this step by step in R. Here's a complete, practical approach that'll get you those runtime comparison curves:
Step 1: Prep Your Functions
First, make sure your helper functions a(), b(), and c() are properly defined (you didn't include them in your question, so I'll use placeholder examples here):
# Example helper functions (replace with your actual ones) a <- function(x) x^2 b <- function(x) sqrt(x) c <- function(x) lgamma(x) # Your original functions f1 <- function(n) { sum = 0 for(i in 1:n) { sum <- sum + a(i) } return(sum) } f4 <- function(n) { sum = 0 for(i in 1:n) { sum <- sum + b(i) } return(sum) } f3 <- function(n) { # Done using lgamma sum = 0 for(i in 1:n) { sum = sum + c(i) } return(sum) }
Step 2: Define Test Parameters
Choose a range of n values to test, and decide how many times to replicate each run (to smooth out random timing noise):
# Range of n values to test (adjust based on your function speed) n_values <- seq(1, 1000, by = 50) # Number of replications per n to get reliable average times n_reps <- 10
Step 3: Measure Runtime for Each Function
Loop through each n value, measure the user CPU time (using system.time's user.self component) for each function, and store the averages:
# Initialize vectors to store average runtime time_f1 <- numeric(length(n_values)) time_f4 <- numeric(length(n_values)) time_f3 <- numeric(length(n_values)) # Run timing loop for (i in seq_along(n_values)) { current_n <- n_values[i] # Measure f1's average user time time_f1[i] <- mean(replicate(n_reps, system.time(f1(current_n))["user.self"])) # Measure f4's average user time time_f4[i] <- mean(replicate(n_reps, system.time(f4(current_n))["user.self"])) # Measure f3's average user time time_f3[i] <- mean(replicate(n_reps, system.time(f3(current_n))["user.self"])) }
Step 4: Create a Plotable Data Frame
Combine the results into a tidy data frame for easier plotting:
runtime_data <- data.frame( n = rep(n_values, 3), avg_user_time = c(time_f1, time_f4, time_f3), function = rep(c("f1", "f4", "f3"), each = length(n_values)) )
Step 5: Plot the Runtime Curves
You can use either base R or ggplot2 for plotting. Here are both options:
Option 1: Using ggplot2 (Cleaner, More Customizable)
# Install ggplot2 if you haven't already # install.packages("ggplot2") library(ggplot2) ggplot(runtime_data, aes(x = n, y = avg_user_time, color = function)) + geom_line(linewidth = 1.2) + geom_point(size = 2) + labs( title = "Function Runtime Comparison", x = "Input Size (n)", y = "Average User CPU Time (seconds)", color = "Function" ) + theme_minimal()
Option 2: Using Base R (No Extra Packages Needed)
plot(n_values, time_f1, type = "l", col = "red", lwd = 2, xlab = "Input Size (n)", ylab = "Average User CPU Time (seconds)", main = "Function Runtime Comparison") lines(n_values, time_f4, col = "blue", lwd = 2) lines(n_values, time_f3, col = "green", lwd = 2) legend("topleft", legend = c("f1", "f4", "f3"), col = c("red", "blue", "green"), lwd = 2)
Quick Notes
- Adjust
n_valuesandn_repsbased on your functions: if your functions are very fast, use largern(e.g., 10,000) and more reps (e.g., 100) to get measurable times. If they're slow, stick to smallernand fewer reps. - The
user.selfvalue fromsystem.timeisolates the CPU time used directly by your function, ignoring system overhead or waiting time. - If your functions have side effects (like modifying global variables), reset their state between replications to avoid skewed results.
内容的提问来源于stack exchange,提问作者Suhail Gupta

