先上一个例子,这段代码是为了评估一个预测模型写的,详细评价说明在

https://www.kaggle.com/c/how-much-did-it-rain/details/evaluation,

它的核心是要计算

在实际计算过程中,n很大(1126694),以至于单进程直接计算时间消耗巨大(14分10秒),

所以这里参考mapReduce的思想,尝试使用多进程的方式进行计算,即每个进程计算一部分n,最后将结果相加再计算C

代码如下:

import csv
import sys
import logging
import argparse
import numpy as np
import multiprocessing
import time # configure logging
logger = logging.getLogger("example") handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s %(name)s: %(message)s')) logger.addHandler(handler)
logger.setLevel(logging.DEBUG) def H(n, z):
return (n-z) >= 0 def evaluate(args, start, end):
'''handle range[start, end)'''
logger.info("Started %d to %d" %(start, end))
expReader = open('train_exp.csv','r')
expReader.readline()
for i in range(start):
_ = expReader.readline()
predFile = open(args.predict)
for i in range(start+1):
_ = predFile.readline()
predReader = csv.reader(predFile, delimiter=',')
squareErrorSum = 0
totalLines = end - start
for i, row in enumerate(predReader):
if i == totalLines:
logger.info("Completed %d to %d" %(start, end))
break
expId, exp = expReader.readline().strip().split(',')
exp = float(exp)
predId = row[0]
row = np.array(row, dtype='float')
#assert expId == predId
#lineSum = 0
for j in xrange(1,71):
n = j - 1
squareErrorSum += (row[j]-(n>=exp))**2
#squareErrorSum += (row[j]-H(n,exp))**2
#lineSum += (row[j]-H(n,exp))**2
logger.info('SquareErrorSum %d to %d: %f' %(start, end, squareErrorSum))
return squareErrorSum def fileCmp(args):
'''check number of lines in two files are same'''
for count, line in enumerate(open('train_exp.csv')):
pass
expLines = count + 1 - 1 #discare header
for count, line in enumerate(open(args.predict)):
pass
predictLines = count + 1 - 1
print 'Lines(exp, predict):', expLines, predictLines
assert expLines == predictLines
evaluate.Lines = expLines if __name__ == "__main__":
# set up logger
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--predict',
help=("path to an predict probability file, this will "
"predict_changeTimePeriod.csv"))
args = parser.parse_args()
fileCmp(args)
pool = multiprocessing.Pool(processes=multiprocessing.cpu_count())
result = []
blocks = multiprocessing.cpu_count()
linesABlock = evaluate.Lines / blocks
for i in xrange(blocks-1):
result.append(pool.apply_async(evaluate, (args, i*linesABlock, (i+1)*linesABlock)))
result.append(pool.apply_async(evaluate, (args, (i+1)*linesABlock, evaluate.Lines+1)))
pool.close()
pool.join()
result = [res.get() for res in result]
print result
print 'evaluate.Lines', evaluate.Lines
score = sum(result) / (70*evaluate.Lines)
print "score:", score

这里是有几个CPU核心就分成几个进程进行计算,希望尽量榨干CPU的计算能力。实际上运行过程中CPU的占用率也一直是100%

测试后计算结果与单进程一致,计算时间缩短为6分27秒,只快了一倍。

提升没有想象中的大。

经过尝试直接用StringIO将原文件每个进程加载一份到内存在进行处理速度也没有进一步提升,结合CPU的100%占用率考虑看起来是因为计算能力还不够。

看来计算密集密集型的工作还是需要用C来写的:)

C的实现要比python快太多了,单线程只需要50秒就能搞定,详见:

http://www.cnblogs.com/instant7/p/4313649.html

Python的并行求和例子的更多相关文章

  1. python实现并行爬虫

    问题背景:指定爬虫depth.线程数, python实现并行爬虫   思路:    单线程 实现爬虫类Fetcher                 多线程 threading.Thread去调Fet ...

  2. python抓取网页例子

    python抓取网页例子 最近在学习python,刚刚完成了一个网页抓取的例子,通过python抓取全世界所有的学校以及学院的数据,并存为xml文件.数据源是人人网. 因为刚学习python,写的代码 ...

  3. 【MPI】并行求和

    比较简单的并行求和 读入还是串行的 而且无法处理线程数无法整除数据总长度的情况 主要用到了MPI_Bcast MPI_Scatter MPI_Reduce typedef long long __in ...

  4. 快速掌握用python写并行程序

    目录 一.大数据时代的现状 二.面对挑战的方法 2.1 并行计算 2.2 改用GPU处理计算密集型程序 3.3 分布式计算 三.用python写并行程序 3.1 进程与线程 3.2 全局解释器锁GIL ...

  5. Python,while循环小例子--猜拳游戏(三局二胜)

    Python,while循环小例子--猜拳游戏(三局二胜) import random all_choice = ['石头', '剪刀', '布'] prompt = '''(0)石头 (1)剪刀 ( ...

  6. python中并行遍历:zip和map-转

    http://blog.sina.com.cn/s/blog_70e50f090101lat2.html 1.并行遍历:zip和map 内置的zip函数可以让我们使用for循环来并行使用多个序列.在基 ...

  7. python之第一个例子hello world

    python用缩进(四个空格,不是teble)来区分代码块 1. coding=utf-8    字符编码,支持汉字 #!/usr/bin/env python# coding=utf-8print ...

  8. [Spark][Python]DataFrame where 操作例子

    [Spark][Python]DataFrame中取出有限个记录的例子 的 继续 [15]: myDF=peopleDF.where("age>21") In [16]: m ...

  9. [Spark][Python]DataFrame select 操作例子

    [Spark][Python]DataFrame中取出有限个记录的例子 的 继续 In [4]: peopleDF.select("age")Out[4]: DataFrame[a ...

随机推荐

  1. Java虚拟机(JVM)知多少

    本文大量参考:https://www.cnblogs.com/lfs2640666960/p/9297176.html 概述 JVM是JRE的一部分.它是一个虚构出来的计算机,是通过在实际的计算机上仿 ...

  2. Java将字符串格式时间转化成Date格式

    可以通过 new 一个 SimpleDateFormat 对象,通过对象调用parse方法实现 示例代码: String time = "2019-07-23"; SimpleDa ...

  3. django 发送邮件功能

    setting.py # 邮件配置 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.e ...

  4. Python 获得程序 exe 的版本号

    Python 获得程序 exe 的版本号 python中需要安装 pywin32 包 # based on http://stackoverflow.com/questions/580924/pyth ...

  5. angular reactive form

    这篇文章讲了angular reactive form, 这里是angular file upload 组件 https://malcoded.com/posts/angular-file-uploa ...

  6. string::crbegin string::crend

    const_reverse_iterator crbegin() const noexcept;功能:crbegin是最后一个字符,crend第一个字符的前一个.迭代器向左移动是“+”,向右移动是“- ...

  7. C# 之 .net core -- EF code first连接Mysql数据库

    一.在Models 新建两个数据库类 这个是数据库需要生成的类基础(塑造外观) public class User { [Key] public string ID { get; set; } [Ma ...

  8. vue初级尝试

    为了跟上前端后台化的潮流,本少不得不开始关注vue,下列上机代码是针对App.vue进行的更改 数据渲染----一般键值对,数组,对象和对象数组 <template> <div id ...

  9. 51nod 1989 竞赛表格 (爆搜+DP算方案)

    题意 自己看 分析 其实统计出现次数与出现在矩阵的那个位置无关.所以我们定义f(i)f(i)f(i)表示iii的出现次数.那么就有转移方程式f(i)=1+∑j+rev(j)=if(j)f(i)=1+\ ...

  10. python-platform模块:平台相关属性

    import platform x=platform.machine() #返回平台架构 #AMD64 x=platform.node() #网络名称(主机名) #DESKTOP-KIK668C x= ...