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

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. ListSetAndMap

    package com.collection.test; import java.util.ArrayList; import java.util.HashMap; import java.util. ...

  2. Educational Codeforces Round 37-F.SUM and REPLACE (线段树,线性筛,收敛函数)

    F. SUM and REPLACE time limit per test2 seconds memory limit per test256 megabytes inputstandard inp ...

  3. easyui tree选中指定节点,点击指定节点

    功能需求描述如下: A主页面,在datagrid的某行上,操作列,点击详情,Tab页面上加载B页面 B页面,左边是树tree,右边是左边树的详情列表 要求:由A页面链接到B页面,B页面的tree,默认 ...

  4. 技术学到多厉害,才能顺利进入BAT?

    简介 本科的时候对 Linux 特别感兴趣,心中向往成为一名运维工程师,就开始没日没夜的看相关的书籍,到了大约2013年前后的时候发现 DevOps 开始流行起来了,就开始学习 Python 希望成为 ...

  5. ubuntu卸载/更新Cmake

    CMake安装或CMake Error at CMakeLists 发生情景: 使用cmake命令安装软件时,报如下错误: CMake Error at CMakeLists.txt:4 (CMAKE ...

  6. R的数据结构--向量

    向量:用于存储数值型.字符型或逻辑型数据的一维数组,只可以包含一种数据 向量的创建与运算 创建向量 # 创建简单向量 l <- c(2, 2, 1, 3, 8) # [1] 2 2 1 3 8 ...

  7. CSS性能优化的8个技巧

    本文作者:高峰,360奇舞团前端工程师,W3C性能工作组成员,同时参与WOT工作组的学习. 我们都知道对于网站来说,性能至关重要,CSS作为页面渲染和内容展现的重要环节,影响着用户对整个网站的第一体验 ...

  8. 题解 [BZOJ4144] Petrol

    题目描述 ​ 有一张 n 个点 m 条边的无向图,其中有 s 个点上有加油站.有 Q 次询问(a,b,c), 问能否开一辆油箱容积为 c 的车从 a 走到 b.(a,b均为加油站) 输入格式 ​ 第一 ...

  9. 【VS调试】VS调试的时候使用IP地址,局域网的设备可以访问并调试

    使用IIS Express调试,只能通过  http://localhost:端口  进行访问 客户端的设备如何才能通过 http://ip地址:端口 访问后台程序进行调试呢? 第一步,打开项目属性, ...

  10. Ubuntu操作及Linux基础知识

    part 1: Ubuntu操作基础 1.调整字体的大小 调大:crtl+shift+“+”  调小:crtl+“-” 2.不要把虚拟机全屏的时候截屏,要不然会认为是Linux系统截屏而非Window ...