【问题标题】:system freezes on running a python script系统在运行 python 脚本时冻结
【发布时间】:2016-07-01 06:39:43
【问题描述】:

我正在编写用于多个信号的基线校正的代码。代码的结构是这样的。

# for each file in a directory
    #read file and populate X vector
    temp = baseline_als(x,1000,0.00001)
    plt.plot(x-temp)
    plt.savefig("newbaseline.png")
    plt.close()

baseline_als函数如下。

def baseline_als(y, lam, p, niter=20):
        L = len(y)
        D = sparse.csc_matrix(np.diff(np.eye(L), 2))
        w = np.ones(L)
        for i in xrange(niter):
            W = sparse.spdiags(w, 0, L, L)
            Z = W + lam * D.dot(D.transpose())
            z = spsolve(Z, w*y)
            w = p * (y > z) + (1-p) * (y < z)
        return z

现在,当我将大约 100 个文件放在一个目录中时,代码可以正常工作,尽管由于复杂性非常高,这需要时间。但是当我的目录中有大约 10000 个文件然后我运行这个脚本时,系统会在几分钟后冻结。我不介意延迟执行,但是脚本是否应该完成执行?

【问题讨论】:

  • 当代码“冻结”时,您是否运行过任何类型的系统监视器?
  • 我不确定如何运行系统监视器。由于鼠标和键盘变得无响应,我必须重新启动。
  • 你没有说你使用的是哪个操作系统。在启动程序之前启动监视器。如果您必须重新启动,那么可能会发生其他事情。你展示了你的整个代码吗?
  • 我使用的是 ubuntu 14.04。是的,除了文件读取部分之外的整个代码。好的,我将尝试在现在执行之前启动系统监视器。
  • 单核?不 !没有线程?不!你的处理器还活着吗?

标签: python optimization system freeze


【解决方案1】:

我能够通过使用time.sleep(0.02) 来防止我的 CPU 达到 100% 然后冻结。这需要很长时间,但仍然会完成执行。

请注意,在使用此之前您需要import time

【讨论】:

    【解决方案2】:

    当您在过多的文件上运行脚本时,会消耗过多的 RAM,请参阅Why does a simple python script crash my system

    您的程序运行的进程将用于计算的数组和变量存储在 进程内存 内存中,它们在那里累积

    一种可能的解决方法是在子进程中运行baseline_als() 函数。子返回时内存自动释放,见Releasing memory in Python

    在子进程中执行函数:

    from multiprocessing import Process, Queue
    
    def my_function(q, x):
     q.put(x + 100)
    
    if __name__ == '__main__':
     queue = Queue()
     p = Process(target=my_function, args=(queue, 1))
     p.start()
     p.join() # this blocks until the process terminates
     result = queue.get()
     print result
    

    复制自:Is it possible to run function in a subprocess without threading or writing a separate file/script

    这样可以防止 ram 被进程(程序)产生的未引用旧变量消耗

    另一种可能是调用垃圾收集器gc.collect(),但不建议这样做(在某些情况下不起作用)

    更多有用的链接:

    memory usage, how to free memory

    Python large variable RAM usage

    I need to free up RAM by storing a Python dictionary on the hard drive, not in RAM. Is it possible?

    【讨论】:

      猜你喜欢
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      • 2016-12-19
      • 2014-08-19
      相关资源
      最近更新 更多