python频繁写入文件怎么提速


本文摘自php中文网,作者尚,侵删。

问题背景:有一批需要处理的文件,对于每一个文件,都需要调用同一个函数进行处理,相当耗时。

有没有加速的办法呢?当然有啦,比如说你将这些文件分成若干批,每一个批次都调用自己写的python脚本进行处理,这样同时运行若干个python程序也可以进行加速。

有没有更简单的方法呢?比如说,我一个运行的一个程序里面,同时分为多个线程,然后进行处理?

大概思路:将这些个文件路径的list,分成若干个,至于分成多少,要看自己cpu核心有多少,比如你的cpu有32核的,理论上就可以加速32倍。

代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

# -*-coding:utf-8-*-

import numpy as np

from glob import glob

import math

import os

import torch

from tqdm import tqdm

import multiprocessing

label_path = '/home/ying/data/shiyongjie/distortion_datasets/new_distortion_dataset/train/label.txt'

file_path = '/home/ying/data/shiyongjie/distortion_datasets/new_distortion_dataset/train/distortion_image'

save_path = '/home/ying/data/shiyongjie/distortion_datasets/new_distortion_dataset/train/flow_field'

r_d_max = 128

image_index = 0

txt_file = open(label_path)

file_list = txt_file.readlines()

txt_file.close()

file_label = {}

for i in file_list:

    i = i.split()

    file_label[i[0]] = i[1]

r_d_max = 128

eps = 1e-32

H = 256

W = 256

def generate_flow_field(image_list):

    for image_file_path in ((image_list)):

        pixel_flow = np.zeros(shape=tuple([256, 256, 2]))  # 按照pytorch中的grid来写

        image_file_name = os.path.basename(image_file_path)

        # print(image_file_name)

        k = float(file_label[image_file_name])*(-1)*1e-7

        # print(k)

        r_u_max = r_d_max/(1+k*r_d_max**2)  # 计算出畸变校正之后的对角线的理论长度

        scale = r_u_max/128  # 将这个长度压缩到256的尺寸,会有一个scale,实际上这里写128*sqrt(2)可能会更加直观

        for i_u in range(256):

            for j_u in range(256):

                x_u = float(i_u - 128)

                y_u = float(128 - j_u)

                theta = math.atan2(y_u, x_u)

                r = math.sqrt(x_u ** 2 + y_u ** 2)

                r = r * scale  # 实际上得到的r,即没有resize到256×256的图像尺寸size,并且带入公式中

                r_d = (1.0 - math.sqrt(1 - 4.0 * k * r ** 2)) / (2 * k * r + eps)  # 对应在原图(畸变图)中的r

                x_d = int(round(r_d * math.cos(theta)))

                y_d = int(round(r_d * math.sin(theta)))

                i_d = int(x_d + W / 2.0)

                j_d = int(H / 2.0 - y_d)

                if i_d < W and i_d >= 0 and j_d < H and j_d >= 0:  # 只有求的的畸变点在原图中的时候才进行赋值

                    value1 = (i_d - 128.0)/128.0

                    value2 = (j_d - 128.0)/128.0

                    pixel_flow[j_u, i_u, 0] = value1  # mesh中存储的是对应的r的比值,在进行畸变校正的时候,给定一张这样的图,进行找像素即可

                    pixel_flow[j_u, i_u, 1] = value2

# 保存成array格式

        saved_image_file_path = os.path.join(save_path, image_file_name.split('.')[0] + '.npy')

        pixel_flow = pixel_flow.astype('f2')  # 将数据的格式转换成float16类型, 节省空间

        # print(saved_image_file_path)

        # print(pixel_flow)

        np.save(saved_image_file_path, pixel_flow)

    return

if __name__ == '__main__':

    file_list = glob(file_path + '/*.JPEG')

    m = 32

    n = int(math.ceil(len(file_list) / float(m)))  # 向上取整

    result = []

    pool = multiprocessing.Pool(processes=m)  # 32进程

    for i in range(0, len(file_list), n):

        result.append(pool.apply_async(generate_flow_field, (file_list[i: i+n],)))

    pool.close()

    pool.join()

在上面的代码中,函数

阅读剩余部分

相关阅读 >>

对numpy 数组和矩阵的乘法的进一步理解

Python如何遍历列表所有元素?

Python中any()和all()使用方法的简单介绍

浅谈Python字符串

django 处理http请求

运行Python脚本的方法是什么

Python如何终止线程

Python的内置函数有哪些

Python内置类属性是什么?如何调用Python内置类属性?

Python中的super函数如何实现继承?

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...