Zacharia2 / SuperMemo-Toolkit

SuperMemo 增强工具(CLI命令行)。包含图链整理、EPUB图书转换导入、Latex公式转图片等。
GNU General Public License v2.0
25 stars 3 forks source link

缩短读取文件时间 #25

Closed Zacharia2 closed 8 months ago

Zacharia2 commented 8 months ago
'''
时间:2021.8.11
作者:手可摘星辰不去高声语
名称:08-案例-视频文件视频的拷贝.py
'''

# 1.导入包和模块
import multiprocessing
import os

def copy_file(file_name, source_dir, dest_dir):
    print(file_name, "--拷贝的进程pid是:", os.getpid())
    # 1.拼接源文件路径和目标文件所在的路径
    source_path = source_dir + "/" + file_name
    dest_path = dest_dir + "/" + file_name
    # 2.打开源文件和目标文件
    with open(source_path, "rb") as source_file:
        with open(dest_path, "wb") as dest_file:
            # 3.循环读取源文件到目标路径
            while True:
                data = source_file.read(1024)
                if data:
                    dest_file.write(data)
                else:
                    break

if __name__ == '__main__':
    # 1.定义源文件夹和目标文件夹
    source_dir = "源文件夹"
    dest_dir = "目标文件夹"

    # 2.创建目标文件夹
    try:
        os.mkdir(dest_dir)
    except:
        print("目标文件夹已经存在!")

    # 3.读取源文件夹的文件列表
    file_list = os.listdir(source_dir)

    # 4.遍历文件列表实现拷贝
    for file_name in file_list:
        # copy_file(file_name, source_dir, dest_dir)
        # 5.使用多进程实现多任务拷贝
        sub_process = multiprocessing.Process(target=copy_file,
                                              args=(file_name, source_dir, dest_dir))
        sub_process.start()
Zacharia2 commented 8 months ago
# -*- coding:utf-8 -*-
# py3

def list_split(list: list, n: int) -> list:
    return [list[i : i + n] for i in range(0, len(list), n)]

if '__main__' == __name__:
    list1 = ['s1', 's2', 's3', 's4', 's5', 's6', 's7']
    # 将数组 list1 每 3 个切分一次
    list2 = list_split(list1, 3)
    print(list2)
Zacharia2 commented 8 months ago

多线程用不用都一样

Zacharia2 commented 8 months ago

多进程,感觉就像复制粘贴了多个py文件一起执行

Zacharia2 commented 8 months ago

异步也不能加快,因为是CPU密集型的任务

Zacharia2 commented 8 months ago

原来是文件读取的io等待问题导致的慢。用多线程等待。数据收集完成后在干别的。

Zacharia2 commented 8 months ago

concurrent.futures库

Zacharia2 commented 8 months ago

文件读取时间是大头。不能靠读取文件内容计算差异,而要避免这个。

最终可行性大概就是读取文件属性的最后修改时间,进行差异对比,筛选出来。

Zacharia2 commented 8 months ago

os.path.getmtime(filename)