Python的多线程与多进程实践

最近要产生大量的”假“的电话号码,所以就写了一个自动产生电话号码程序,产生了一百万条数据,然后把数据放到一个文件中。

死跑版:

# -*- coding: utf-8 -*-
# 以下是中国的手机号码分段情况
#   新联通  (中国联通+中国网通)手机号码开头数字 130、131、132、145、
               # 155、156、185、186
#   新移动  (中国移动+中国铁通)手机号码开头数字 134、135、136、137、
               # 138、139、147、150、151、152、157、158、159、182、183、187、188
#   新电信  (中国电信+中国卫通)手机号码开头数字 133、153、189、180
# this script generates telephone numbers in mobile_china, unicom_china,tele_china
import random
from random import choice
import time# mobile info
mobile_china = [‘134‘,‘135‘,‘136‘,‘137‘,‘138‘,‘139‘,‘147‘,‘150‘,‘151‘,‘152‘,‘157‘,‘158‘,‘159‘,‘182‘,‘183‘,‘187‘,‘188‘ ]
unicom_china = [‘130‘,‘131‘,‘132‘,‘145‘,‘155‘,‘156‘,‘185‘,‘186‘]
tele_china = [‘133‘,‘153‘,‘189‘,‘180‘]
# the heading three numbers of a telephone number
all_three = mobile_china + unicom_china + tele_china
# the tailing eight numbers of a telephone number
all_eight = 99999999
# 1 million -- the total counts of telephone number
# 100 million records is too much for my computer
Max = 1000000
def telenum_gen():
    # create a file
    tele_book = open(‘tele_book_solo.txt‘,‘w‘)
    for i in xrange(Max):
        three = choice(all_three)
        eight = str(random.randint(0,all_eight)).rjust(8,‘0‘)
        tele_num = three + eight
        print "now the %r th record is %r " %(i,tele_num)
        tele_book.write(tele_num+"\n")
    tele_book.close()

# begin time
start = time.clock()

telenum_gen()
# end time
end = time.clock()
print "Running time is %d seconds." %(end-start)

算法很简单,把所有可能的中国联通,中国移动,还有中国电信的前三位号码放到一个列表中,后面八位随机数产生,然后二者拼接成字符串即可。

但是这个运行时间太慢了,运行了4000多秒。如果要产生1亿条数据,计算机直接挂掉了。

于是就考虑,能不能使用多线程或者多进程呢?

于是,就有了多线程版本的电话号码生成器:

多线程版:

# -*- coding: utf-8 -*-
# 以下是中国的手机号码分段情况
#   新联通  (中国联通+中国网通)手机号码开头数字 130、131、132、145、
               # 155、156、185、186
#   新移动  (中国移动+中国铁通)手机号码开头数字 134、135、136、137、
               # 138、139、147、150、151、152、157、158、159、182、183、187、188
#   新电信  (中国电信+中国卫通)手机号码开头数字 133、153、189、180
# this script generates telephone numbers in mobile_china, unicom_china,tele_china
import random
from random import choice
import time
import threading 

# mobile info
mobile_china = [‘134‘,‘135‘,‘136‘,‘137‘,‘138‘,‘139‘,‘147‘,‘150‘,‘151‘,‘152‘,‘157‘,‘158‘,‘159‘,‘182‘,‘183‘,‘187‘,‘188‘ ]
unicom_china = [‘130‘,‘131‘,‘132‘,‘145‘,‘155‘,‘156‘,‘185‘,‘186‘]
tele_china = [‘133‘,‘153‘,‘189‘,‘180‘]
# the heading three numbers of a telephone number
all_three = mobile_china + unicom_china + tele_china
# the tailing eight numbers of a telephone number
all_eight = 99999999
# 1 million -- the total counts of telephone number
# 100 million records is too much for my computer
Max = 1000000
worker_num = 5

def telenum_gen(file):
    split_work = Max/worker_num
    for i in xrange(split_work):
        three = choice(all_three)
        eight = str(random.randint(0,all_eight)).rjust(8,‘0‘)
        tele_num = three + eight
        file.write(tele_num+"\n")
        print "now the %r th record is %r " %(i,tele_num)

if __name__ == ‘__main__‘:
    # begin time
    start = time.clock()
    threads = []
    tele_book = open(‘tele_book_thread.txt‘,‘w‘)
    for x in xrange(worker_num):
        threads.append(threading.Thread(target=telenum_gen,args=(tele_book,)))
    #begin to work
    for worker in threads:
        worker.start()
    for worker in threads:
        worker.join()
    tele_book.close()
    # end time
    end = time.clock()
    print "Running time is %d seconds." %(end-start)

产生了5个线程,共同对同一个文件做写入操作。

结果,运行时间要比直接产生还要慢,我实验了10万条数据,慢了20秒左右。

于是,又想,是不是多进程会更好一点呢?就查找资料,写了多进程版本的:

多进程版:

# -*- coding: utf-8 -*-
# 以下是中国的手机号码分段情况
#   新联通  (中国联通+中国网通)手机号码开头数字 130、131、132、145、
               # 155、156、185、186
#   新移动  (中国移动+中国铁通)手机号码开头数字 134、135、136、137、
               # 138、139、147、150、151、152、157、158、159、182、183、187、188
#   新电信  (中国电信+中国卫通)手机号码开头数字 133、153、189、180
# this script generates telephone numbers in mobile_china, unicom_china,tele_china
import random
from random import choice
import time
import multiprocessing
from multiprocessing import Process
# mobile info
mobile_china = [‘134‘,‘135‘,‘136‘,‘137‘,‘138‘,‘139‘,‘147‘,‘150‘,‘151‘,‘152‘,‘157‘,‘158‘,‘159‘,‘182‘,‘183‘,‘187‘,‘188‘ ]
unicom_china = [‘130‘,‘131‘,‘132‘,‘145‘,‘155‘,‘156‘,‘185‘,‘186‘]
tele_china = [‘133‘,‘153‘,‘189‘,‘180‘]
# the heading three numbers of a telephone number
all_three = mobile_china + unicom_china + tele_china
# the tailing eight numbers of a telephone number
all_eight = 99999999
# 1 million -- the total counts of telephone number
# 100 million records is too much for my computer
Max = 100000
worker_num = 5
# input worker
def telenum_gen(queue):
    split_work = Max/worker_num
    for i in xrange(split_work):
        three = choice(all_three)
        eight = str(random.randint(0,all_eight)).rjust(8,‘0‘)
        tele_num = three + eight
        queue.put(tele_num)
        print "now the %r th record is %r " %(i,tele_num)
# output worker
def write_telenum(queue):
    split_work = Max/worker_num
    tele_book = open(‘tele_book_process.txt‘,‘a‘)
    for i in xrange(split_work):
        tele_num = queue.get()
        tele_book.write(tele_num+"\n")
    tele_book.close()

if __name__ == ‘__main__‘:
    print "author: YQ"
    # begin time
    start = time.clock()
    # define input worker list and output worker list of a queue
    input_workers = []
    output_workers = []

    lock  = multiprocessing.Lock()    # To prevent file exception
    queue = multiprocessing.Queue(-1)
    # open a file 

    # input process
    for x in xrange(worker_num):
        process = multiprocessing.Process(target=telenum_gen,args=(queue,))
        process.start()
        input_workers.append(process)
    for x in xrange(worker_num):
        process = multiprocessing.Process(target=write_telenum,args=(queue,))
        process.start()
        output_workers.append(process)
    #begin to work
    print "this is the length of input workers:",len(input_workers)
    for p in input_workers:
        p.join()
    queue.close()  # No more object will come, close the queue
    # write_telenum(queue,tele_book)
    for p in output_workers:
        p.join()
    # end time
    end = time.clock()
    print "Running time is %d seconds." %(end-start)

做成模式类似于生产者和消费者,一些进程产生数据,放到队列中;另外的一些进程读取数据,并写入到文件中。

由于每个进程都有自己独立的内存空间,所以对消费者进程来讲,不能像线程那样,共享一个文件的句柄,每个进程只能依次执行打开文件,写入,关闭的操作。

运行的结果,依然没有任何起色,与线程版本的运行时间差不多。

总结:

就我的应用场景来说,完全没有必要进行多进程或者多线程,有没有密集的IO操作,没有阻塞,使用多进程或者多线程反而拖累了程序的运行速度。

参考:

Python多进程并发(multiprocessing)

Python标准库10 多进程初步 (multiprocessing包)(作者:Vamei 出处:http://www.cnblogs.com/vamei)

时间: 2024-08-26 14:27:39

Python的多线程与多进程实践的相关文章

Python的多线程和多进程模块对比测试

本文主要对比测试Python的多线程和多进程模块在CPU类型和I/O的任务操作时的效率 一 测试CPU消耗类型任务 在一台多核CPU的服务器上执行多线程代码,理论上代码执行时会利用多余的CPU核心来提升性能.但是由于Python的GIL的存在,使用多线程来执行CPU繁重的任务,未必能得到性能提升.但是GIL又必不可少,因为在Python解释器中执行线程是不安全的,也就是说为了保证Python线程执行时的安全,Python提供了一个全局锁,同一时刻,只允许一个线程获得这个全解锁并执行. CPU消耗

python socket多线程和多进程

在socket中,如果直接创建的话,是只能接受一个用户的请求需要实现socketserver中的handle方法,可以实现多进程并发访问 SocketServer内部使用 IO多路复用 以及 "多线程" 和 "多进程" ,从而实现并发处理多个客户端请求的Socket服务端.即:每个客户端请求连接到服务器时,Socket服务端都会在服务器是创建一个"线程"或者"进 程" 专门负责处理当前客户端的所有请求. 1.创建一个继承自 s

python的多线程和多进程

要使用Python的多线程,首先要了解一个概念.GIL(global interpreter lock),翻译过来就是以解释器为单位的全局锁. 用过线程锁的都知道,LOCK就是用来管理住线程,让一个指定的线程先运行,其他的先暂停(等待),避免线程的混乱,尤其是在共用变量的情况下. GIL也是一样的概念,但是不同的是: 1.你可以想成他是解释器控制的 2.线程的指定是随机的 3.每个线程acquire运行机会后,可运行的内容很少(因此线程间的切换超级快) 因此,多线程看起来好像是多个线程一起运行,

python中多线程,多进程,队列笔记(一)

threading简介:If you want your application to make better use of the computational resources of multi-core machines, you are advised to use multiprocessing. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks si

python之多线程与多进程

1. 多进程与多线程 (1)背景:为何需要多进程或者多线程:在同一时间里,同一个计算机系统中如果允许两个或者两个以上的进程处于运行状态,这便是多任务.多任务会带来的好处例如用户边听歌.边上网.边打印,而这些任务之间丝毫不会互相干扰.使用多进程技术,可大大提高计算机的运算速率. (2)多进程与多线程的区别: 进程:程序在计算机上的一次执行活动.进程分为:系统进程和用户进程. 当运行一个程序时,实际就是启动了一个进程.程序是死的(静态的),进程是活的(动态的). 线程:是程序中的一个单一的顺序控制流

python的多线程、多进程代码示例

多线程有两种方式:thread和threading 这里应用的场景是map数据分多线程.进度写入codis的示例 这是thread的示例:thread的主进程不会等待线程 import thread,math,threading,multiprocessing,os,time def writeToCodis(prefix,key_list,result_map): # client = BfdCodis("xxx", ) begin = int(time.time()) for ke

基于Python的多线程与多进程

1.I/O密集型与计算密集型 多进程适用于I/O密集型 多进程适用于计算密集型 2.没有sleep(T)的多个死循环只能用多进程 3.模块介绍: 1)threading模块(_thread模块已淘汰)示例: 运行结果: 2)multiprocessing 模块演示: 代码结果: 3) concurrent.futures模块 执行结果: 原文地址:https://www.cnblogs.com/cepaAllium/p/11528994.html

appium 多线程还是多进程(转)

https://www.cnblogs.com/zouzou-busy/p/11440175.html 在前面我们都是使用一个机器进行测试,在做app自动化的时候,我们要测不同的机型,也就是兼容性测试,如果一台一台设备去执行,那就显的太麻烦了.所以经常需要我们启动多个设备,同时跑自动化测试用例,要跑多个设备时,首先要启动多个appium服务. 启动多个appium服务 在之前我们都是在命令行里输入appium来启动appium服务,这样启动的默认端口是4723,我们可以使用-p参数来指定端口号,

python多线程、多进程以及GIL

多线程 使用threading模块创建线程 传入一个函数 这种方式是最基本的,即调用threading中的Thread类的构造函数,然后指定参数target=func,再使用返回的Thread的实例调用start()方法,即开始运行该线程,该线程将执行函数func,当然,如果func需要参数,可以在Thread的构造函数中传入参数args=(-).示例代码如下 import threading #用于线程执行的函数 def counter(n): cnt = 0; for i in xrange