2
\$\begingroup\$

I want to check the memory usage of a process before and after I copy a large file or folder, and also, I want to get the maximum memory usage during file operation. Is this a good method?

def copy_folder(s,d):
    if os.path.isdir(d):
        shutil.rmtree(d)
    shutil.copytree(s, d)
    return get_folder_size(s)

def get_pid(process_exe):
    pid = []
    for proc in psutil.process_iter():
        try:
            if proc.name() == process_exe:
                pid.append(proc.pid)
        except psutil.AccessDenied:
            pass
    return pid[0]

def get_process_memory_usage(process_exe):
    pid = get_pid(process_exe)
    process = psutil.Process(pid)
    process_memory = process.memory_info()[0] / float(2 ** 20)
    return process_memory


def get_process_max_memory_usage(process, funct, source, dest):
    t = threading.Thread(target=funct, args=(source, dest))
    t.start()
    memory_vals = []
    if t.isAlive():
        while t.isAlive():
            memory_vals.append(get_process_memory_usage(process))
            time.sleep(1)
        return max(memory_vals), memory_vals
    else:
        return "Thread not found"

this is how I call the function: get_max_memory_usage("process", copy_folder, source, destination)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.