在Python中优化文件和数字行计数

2024-04-23 14:56:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了一个python项目,有许多文件夹、文件(.css、.py、.yml等)和代码行。对于这个项目,我制作了一个名为“统计”的工具,它为我提供了整个项目的信息,例如:

Global statistics:

Entire project :: 32329 lines
Project main files (.py, .yml) :: 8420 lines
Project without vendor part :: 1070 lines
Core (src directory) :: 394 lines
Core compared to project main files :: 5 % Kraken Framework (vendor/*.py) :: 7350 lines
Main files Python code :: 93 %
Vendor Python code :: 87 %
Entire project size :: 37M

为了得到所有这些数字,我主要使用两个函数:

def count_folder_lines(self, path):
    files = glob.glob(path, recursive=True)
    number = 0
    for file in files:
        num_lines = sum(1 for line in open(file))
        number += num_lines
    return number

以及

def count_number_of_files(self, path):
    files = glob.glob(path, recursive=True)
    return len(files)

第一个用于计算文件夹中的行数,第二个用于计算特定文件的数量(例如:src/*.py)。 但要得到项目的统计数据,需要4.9秒到5.3秒之间,这是非常多的。你知道吗

有什么办法让它更快吗?并行编程或使用Cython会改变什么吗?你知道吗

祝你今天愉快, 非常感谢。你知道吗


Tags: 文件path项目pyproject文件夹numbermain
1条回答
网友
1楼 · 发布于 2024-04-23 14:56:46

终于为我找到了最有效的解决方案: 我使用多处理模块来并行计算每个文件的行数。你知道吗

def count_folder_lines(self, path):
    """ 
        Use a buffer to count the number of line of each file among path.
        :param path: string pattern of a file type
        :return: number of lines in matching files
    """
    files = glob.glob(path, recursive=True)
    number = 0
    for file in files:
        f = open(file, 'rb')
        bufgen = takewhile(lambda x: x,
                           (f.raw.read(1024 * 1024) for _ in repeat(None)))
        number += sum(buf.count(b'\n') for buf in bufgen if buf)
    return number

def count_number_of_files(self, path):
    """
        Count number of files for a string pattern
        :param path: files string pattern
        :return: number of files matching the pattern
    """
    files = glob.glob(path, recursive=True)
    return len(files)

def multiproc(self):
    """
        Multiprocessing to launch several processes to count number of
        lines of each string pattern in self.files
        :return: List of number of files per string pattern
                    (list of int).
    """
    pool = mp.Pool()
    asyncResult = pool.map_async(self.count_folder_lines, self.files)
    return asyncResult.get()

使用此解决方案,计数需要~1.2秒,而之前需要~5秒。

祝你今天愉快!你知道吗

相关问题 更多 >