我试图通过在随机值列表中查找素数来研究线程。我期望发现使用线程使得这个更快,但线程和非线程的时间是相同的。这是因为我错误地实现了这个吗?如何使用这样的示例演示线程的好处?
import time
import threading
from math import sqrt
from random import randint
def findPrimes(aList):
for testValue in aList:
isPrime = True
for i in range(2,int(sqrt(testValue)+1)):
if testValue % i == 0:
isPrime = False
if isPrime:
#print(testValue)
pass
testValues1 = []
testValues2 = []
for i in range(1000):
testValues1.append(randint(10,100))
testValues2.append(randint(10,100))
t = time.process_time()
findPrimes(testValues1)
findPrimes(testValues2)
print('The long way',time.process_time() - t) # runs in 0.006 to 0.007
t = time.process_time()
thread1 = threading.Thread(target=findPrimes(testValues1))
thread2 = threading.Thread(target=findPrimes(testValues2))
thread1.start()
thread2.start()
print('The threading way',time.process_time() - t) # also runs in 0.006 to 0.007
答案 0 :(得分:0)
Python中的线程仅对IO绑定操作有用,因为全局解释器锁(GIL)实质上迫使Python操作以锁步方式发生,从不实际并发。
(但是,执行IO的线程,例如与远程服务器通信或访问文件,通常比没有线程更快。)
请参阅How to use threading in Python?以获取解决方案,例如使用{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "http://some.thing/json",
"type": "object",
"definitions": {
"value": {
"$id": "/definitions/value",
"type": "object",
"required": [
"a",
"b",
"c"
],
"properties": {
"a": {
"$id": "/properties/value/a",
"type": "string"
},
"b": {
"$id": "/properties/value/b",
"type": "string"
},
"c": {
"$id": "/properties/value/c",
"type": "string"
}
}
}
},
"required": [
"values"
],
"properties": {
"values": {
"$id": "/properties/values",
"type": "array",
"items": {
"$ref": "/definitions/value"
}
},
"uniqueItems": true
}
}
模块。
答案 1 :(得分:0)
线程并不是同时运行的......线程的概念是一个特定的线程能够与许多其他线程共享cpu时钟周期,这些线程似乎可以模仿并发行为,但它们并不是并行运行