使用多线程比使用循环

时间:2016-08-20 14:49:17

标签: python multithreading multiprocessing

我有以下股票价格模拟,我运行了40年(= 10400价格):

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import random
import itertools
from multiprocessing.pool import ThreadPool
from timeit import default_timer as timer

def stock_simulation(k, runs):
    start = timer()
    stock_vals = pd.DataFrame(columns=['date'], index = [-1])
    stock_val = stock_calc(100, 0, 0)
    stock_vals = stock_val
    j = 1
    for i in range(runs):
        risky_return = mu + (sigma * random.gauss(0,1))
        bonus = random.gauss(0,1)

        stock_val = stock_calc(stock_val['stock_val'], risky_return, bonus)
        stock_vals = stock_vals.append(stock_val)
        j = j + 1

    end = timer()
    print('Iteration ' + str(k) + ' took: ' + str(round(end - start, 2)))

def stock_calc(old_val, perf_risky, bonus):
    stock = pd.DataFrame(columns=['date'], index = [1])
    stock['date'] = 1

    stock['stock_val'] = (1 + perf_risky) * old_val + bonus * old_val
    return(stock)

#Simulation
exp_return = 0.05
exp_vola = 0.08
trading_days = 260
mu = exp_return / trading_days
sigma = exp_vola * np.sqrt(1 / trading_days)
print('Enter the number of runs')
NoOfRuns = input()
print('Es werden ' + str(NoOfRuns) + ' Simulationen durchgeführt.')
T = int(NoOfRuns)

#Multithreading
total_start = timer()
pool = ThreadPool(4)
pool.starmap(stock_simulation, zip(range(T), itertools.repeat(10400)))
pool.close() 
pool.join()
total_end = timer()
print(str(T) + ' were run in total and it took: ' + str(round(total_end - total_start, 2)))


total_start = timer()
for k in range(T):
    stock_simulation(k + T, 10400)
total_end = timer()
print(str(T) + ' were run in total and it took: ' + str(round(total_end - total_start, 2)))

运行几次后,多线程版本比循环版本慢约12%。我不知道为什么会这样。我不能多线程更长的循环,因为它使用前一次迭代运行10400次。

0 个答案:

没有答案