You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言中如何简便统计for循环各命令的迭代平均耗时?

R语言循环中矩阵求逆的批量计时方案

不需要手动重复写Sys.time()计算差值,可通过封装计时逻辑或利用内置的system.time函数简洁实现,同时统一记录每个矩阵每次求逆的耗时,最后计算平均值。

方法一:批量循环计时 + 结果存储

先初始化列表记录每个矩阵的所有迭代耗时,在循环中对每个solve操作单独计时:

n <- 1000
P <- 3 # 替换为实际的矩阵数量
# 初始化存储时间的列表,每个元素对应一个矩阵的耗时记录
time_records <- vector("list", P)
names(time_records) <- paste0("matrix", 1:P)

for (i in 1:n) {
  # 遍历所有矩阵,计时并存储结果
  for (p in 1:P) {
    # 获取当前矩阵
    current_mat <- get(paste0("matrix", p))
    # 用system.time计时,提取用户CPU时间(可替换为"elapsed"获取总耗时)
    elapsed_time <- system.time({ inv_result <- solve(current_mat) })[["user.self"]]
    # 记录耗时
    time_records[[p]] <- c(time_records[[p]], elapsed_time)
    # 保存求逆结果(如果需要后续使用)
    assign(paste0("command", p), inv_result)
  }
  
  # 矩阵更新逻辑(保持原有代码不变)
  matrix1 <- update(matrix1)
  matrix2 <- update(matrix2)
  matrix3 <- update(matrix3)
  # ... 其余矩阵的更新操作
}

# 计算每个矩阵求逆的平均耗时
average_times <- sapply(time_records, mean)
print(average_times)

方法二:封装计时版solve函数

把计时逻辑封装成独立函数,让循环代码更整洁:

# 封装带计时的solve函数,返回求逆结果和耗时
timed_solve <- function(mat) {
  # 记录solve操作的用户CPU时间
  time_taken <- system.time({ inv_res <- solve(mat) })[["user.self"]]
  list(result = inv_res, time = time_taken)
}

n <- 1000
P <- 3
time_records <- vector("list", P)
names(time_records) <- paste0("matrix", 1:P)

for (i in 1:n) {
  # 对每个矩阵使用封装的计时函数
  res_mat1 <- timed_solve(matrix1)
  command1 <- res_mat1$result
  time_records[[1]] <- c(time_records[[1]], res_mat1$time)
  
  res_mat2 <- timed_solve(matrix2)
  command2 <- res_mat2$result
  time_records[[2]] <- c(time_records[[2]], res_mat2$time)
  
  res_mat3 <- timed_solve(matrix3)
  command3 <- res_mat3$result
  time_records[[3]] <- c(time_records[[3]], res_mat3$time)
  
  # 矩阵更新逻辑
  matrix1 <- update(matrix1)
  matrix2 <- update(matrix2)
  matrix3 <- update(matrix3)
}

# 计算平均耗时
average_times <- sapply(time_records, mean)
print(average_times)

补充说明

  • system.time返回的结果中,user.self是用户CPU耗时,elapsed是实际流逝的总时间,可根据需求选择。
  • 如果需要更精准的微秒级计时,可以使用proc.time()手动计算差值,或者使用microbenchmark包,但上述方法已经足够应对大部分场景,且代码简洁易维护。

内容的提问来源于stack exchange,提问作者androsrj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 11:22:58