操作简单,运行时间长

时间:2016-05-18 06:39:54

标签: python python-2.7 numpy

# PerCoinStatistics.py
class PerCoinStatistics:
    def __init__(self):
        self.total = 0
        self.nHeads = 0


    def head(self):
        self.total += 1
        self.nHeads += 1

    def tail(self):
        self.total += 1

    def getHeads(self):
        return self.nHeads

    def getTotal(self):
        return self.total

    def reset(self):
        self.total = 0
        self.nHeads = 0

# Trial.py
from PerCoinStatistics import PerCoinStatistics
import random

class Trial:

    def __init__(self, nCoins, nFlips):
        self.m_v1 = None
        self.m_vr = None
        self.m_vm = None
        self.m_nCoins = nCoins
        self.m_nFlips = nFlips


    def flip(self, stats, times):
        for i in xrange(0, times):
            r = random.randint(0, 1)
            if 0 == r:
                stats.head();
            else:
                stats.tail();

    def run(self):
        rn = random.randint(0, self.m_nCoins - 1)
        stats = PerCoinStatistics()
        self.m_vm = 1.0;
        # flips all m_nCoins m_nFlips times
        for i in xrange(0, self.m_nCoins):
            self.flip(stats, self.m_nFlips)
            p = stats.getHeads() / float(stats.getTotal())
            if p < self.m_vm:
                self.m_vm = p
            if 0 == i:
                self.m_v1 = p
            if rn == i:
                self.m_vr = p
            stats.reset()

# main.py
from Trial import Trial
import time
import sys
import numpy as np
import matplotlib.pyplot as plt
import random

nTrials = 1000
nCoins = 10
nFlips = 1000
b = 100

Vs = np.ndarray(shape=(3,nTrials), dtype=float, order='C');

random.seed()

startTime = time.time()
for i in xrange(0, nTrials):
    t = Trial(nCoins, nFlips)
    t.run()
    Vs[0][i] = t.m_v1
    Vs[1][i] = t.m_vr
    Vs[2][i] = t.m_vm
    #print "trial #",i,"done:",t.m_v1
endTime = time.time()

print "took ",(endTime - startTime),"secs to run",nTrials,"trials"

sys.stdout.flush()

# plot histogram
plt.subplot(311)

plt.hist(Vs[0], b, facecolor='green')

plt.title('Histogram of V1')
plt.grid(True)

plt.subplot(312)
plt.hist(Vs[1], b, facecolor='red')
plt.title('Histogram of Vr')
plt.grid(True)

plt.subplot(313)
plt.hist(Vs[2], b, facecolor='blue')
plt.title('Histogram of Vm')
plt.grid(True)

plt.show()

该代码生成简单的硬币翻转概率统计信息。由于某种原因,大约每个硬币翻转(包括将概率复制到预先分配的numpy阵列)需要2.9微秒(不包括上图的总时间在我的2.93GHz机器上是~29秒)。

有没有更好的加速方法(除了在多个内核上并行运行试用版)?

谢谢!

0 个答案:

没有答案