【问题标题】:My R function is consuming too much memory. Can you help me optimizing it?我的 R 函数消耗了太多内存。你能帮我优化一下吗?
【发布时间】:2021-12-06 07:07:40
【问题描述】:

我是 R 新手,在优化函数时遇到了麻烦。

我的职责是:

  1. 创建函数中指定的目录
  2. 从函数内的链接下载zip文件并解压到目录
  3. 如果文件是在新的子文件夹下提取的,请将提取的文件移动到主目录
  4. 删除子文件夹

它可以工作,但会消耗大量内存,并且需要 30 分钟才能在 2.7MB 的 zip 文件上完成如此简单的工作。

提前谢谢你!

create_dir <- function(directory) {
  path <- file.path(getwd(), directory)
  if (!file.exists(path)) {
    dir.create(path)
  }
  link <-
    "https://d396qusza40orc.cloudfront.net/rprog%2Fdata%2Fspecdata.zip"
  temp <- tempfile()
  download.file(link, temp, mode = "wb")
  unzip(temp, exdir = path)
  unlink(temp)
  existing_loc <- list.files(path, recursive = TRUE)
  for (loc in existing_loc) {
    if (length(grep("/", loc))) {
      file.copy(file.path(path, loc), path)
      file.remove(file.path(path, loc))
    }
  }
  dirs <- list.dirs(path)
  rm_dirs <- dirs[dirs != path]
  if (length(rm_dirs)) {
    for (dir in rm_dirs) {
      unlink(rm_dirs, recursive = TRUE)
    }
  }
}
create_dir("testDirectory")

【问题讨论】:

  • 你分析过你的函数吗?该 zip 文件中有多少个文件?
  • zip 中的 332 个文件;总共 17.2MB。
  • 感谢@Roland 对 Rprof() 的建议。这是我要探索的新领域。问题在于 OneDrive 和 AntiVirus 会同步和扫描 332 个文件的提取、移动和删除。 setwd()在本地磁盘上运行速度超级快。

标签: r function copy zip move


【解决方案1】:

谢谢,我找到了问题。这是因为在 OneDrive 上设置了一个工作目录,该目录会为该函数处理的 332 个文件的每次提取、移动和删除同步。 AntiVirus 还与 OneDrive 一起运行,导致我的 PC 使用 70% 的 CPU 冻结 30 分钟。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 2020-04-16
    • 2011-09-23
    • 1970-01-01
    相关资源
    最近更新 更多