繁体   English   中英

python中每个函数的内存使用情况

[英]Memory usage per function in python

import time
import logging
from functools import reduce

logging.basicConfig(filename='debug.log', level=logging.DEBUG)



def read_large_file(file_object):
    """Uses a generator to read a large file lazily"""

    while True:
        data = file_object.readline()
        if not data:
            break
        yield data


def process_file_1(file_path):
    """Opens a large file and reads it in"""

    try:
        with open(file_path) as fp:
            for line in read_large_file(fp):
                logging.debug(line)
                pass

    except(IOError, OSError):
        print('Error Opening or Processing file')


    def process_file_2(file_path):
        """Opens a large file and reads it in"""

        try:
            with open(path) as file_handler:
                while True:
                    logging.debug(next(file_handler))
        except (IOError, OSError):
            print("Error opening / processing file")
        except StopIteration:
            pass


    if __name__ == "__main__":
        path = "TB_data_dictionary_2016-04-15.csv"

        l1 = []
        for i in range(1,10):
            start = time.clock()
            process_file_1(path)
            end = time.clock()
            diff = (end - start)
            l1.append(diff)

        avg = reduce(lambda x, y: x + y, l1) / len(l1)
        print('processing time (with generators) {}'.format(avg))


        l2 = []
        for i in range(1,10):
            start = time.clock()
            process_file_2(path)
            end = time.clock()
            diff = (end - start)
            l2.append(diff)

        avg = reduce(lambda x, y: x + y, l2) / len(l2)
        print('processing time (with iterators) {}'.format(avg))

程序输出:

C:\Python34\python.exe C:/pypen/data_structures/generators/generators1.py
processing time (with generators) 0.028033358176432314
processing time (with iterators) 0.02699498330810426

在上面的程序中,我试图用generators iterators来测量用iterators打开读取大文件所用的时间。 该文件位于此处 使用迭代器读取文件的时间比使用生成器读取文件的时间少得多。

我假设如果要测量process_file_1process_file_2函数使用的内存量,则生成器的性能将优于迭代器。 有没有一种方法可以测量python中每个函数的内存使用情况。

首先,使用代码的单次迭代来衡量其性能不是一个好主意。 由于系统性能的任何故障(例如,后台进程,执行垃圾回收的cpu等),结果可能会有所不同。 您应该检查它是否有相同代码的多次迭代。

要测量代码的性能,请使用timeit模块:

此模块提供了一种计时Python小代码的简单方法。 它既具有命令行界面又具有可调用界面。 它避免了许多用于测量执行时间的常见陷阱。

检查代码的内存消耗,请使用Memory Profiler

这是一个python模块,用于监视进程的内存消耗以及逐行分析python程序的内存消耗。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM