【发布时间】:2020-10-12 22:46:11
【问题描述】:
我正在计算图表上方的度量,对每个操作使用顺序大约需要 40 秒,然后我需要进行 38 次此计算,总共 1520 秒或 25 分钟。所以,我想如果我使用线程,这会更快。我有这个使用线程的模板,但我正在检查时间,我注意到,这不是更快,而是慢了近十倍。 这个 lista 是一个带有要使用的索引的列表,来自 x_test(test dataset),v_G 是一个图表列表,N_exp 是执行计算的次数。
这是顺序代码:
import time
start1 = time.time()
v_dist1 = []
for i in range(38):
new_point = X_test[i,:]
print(new_point)
import time
start = time.time()
for G in v_G:
G1 = add_point(G, new_point)
# print( nx.adjacency_matrix(G).toarray() )
v_dist1.append(ant_mod(G1, N_exp))
# print(v_dist1)
end = time.time()
print('time::: ', end - start)
end1 = time.time()
print('time total::: ', end1 - start1)
这是线程代码:
class myThread (threading.Thread):
def __init__(self, lista, x_test, v_G, N_exp, name):
threading.Thread.__init__(self)
self.lista = lista
self.x_test = x_test
self.v_G = v_G
self.N_exp = N_exp
self.name = name
def run(self):
pages = []
# print(self.lista)
size = len(self.lista)
for i in range(0,size):
start = time.time()
for G in v_G:
G1 = add_point(G, self.x_test[self.lista[i]])
pages.append(ant_mod(G1, self.N_exp))
sleep(0.5)
end = time.time()
print('time::: ', end - start)
data = pd.DataFrame(pages)
data.to_csv('prueba'+self.name+'.csv', sep ="¬",encoding='utf-8', index=False)
#l[0] is the list with indexes, I use a number of thread equals
#to number of cores-2, then I replicate this code 6 times.
thread1 = myThread(l[0], X_test, v_G, N_exp, str(N_exp)+'.0')
thread1.start()
thread1.join()
【问题讨论】:
-
您的课堂使用情况如何?请edit您提出问题并提供minimal reproducible example。
-
所以,我想如果我使用线程会更快。 但情况并非总是如此。你只是问为什么代码变慢了?
-
感谢您的回复。我今天刚刚发现错误,我有一个 main 函数,然后我认为声明的变量只有这个函数的范围,但是一些奇怪的原因,我在那里创建的一个 X 可以从另一个函数访问。此外,我忘了添加这个变量作为这个函数的参数。
标签: python multithreading dataframe thread-safety python-multithreading