如何解决Python多股票价格跟踪器
我正在尝试为python中的一组股票创建1分钟的股价跟踪服务器。我编写了一个多线程的python程序,该程序为列表中的每个股票调用我的价格跟踪器功能。这会导致我的计算机上的CPU使用率达到100%左右,并使一切变得非常缓慢。
请您提出一种我应该使用的方法或任何其他工具。
P.S。我也尝试过多处理。
def f(x):
print("Starting process : " + str(x))
time.sleep(5)
if __name__ == '__main__':
while (True):
km = datetime.now().minute
ks = datetime.now().second
if km % 1 == 0 and ks == 1:
print("=>S===> / km = " + str(km) + " | " + " ks = " + str(ks))
for x in range(20):
p = Process(target=f,args=(x,))
p.start()
km = datetime.now().minute
ks = datetime.now().second
print("=>E===> / km = " + str(km) + " | " + " ks = " + str(ks))
time.sleep(1)
p.join()
这是我的代码。函数f是我计划在每分钟开始时进行计算,并且应该为n个股票(代码示例中为20)创建单独的过程
编辑:(1)我完成了以下更改,并认为它将与时钟同步,但是,下面的代码显示的时钟和打印内容不匹配。总是有6秒的延迟。
from multiprocessing import Process
import os
import time
firstRun = True
def f(x):
print("Starting process : " + str(x))
time.sleep(5)
print("Ending process : " + str(x))
if __name__ == '__main__':
while (True):
ks = datetime.now().second
print("//////////////////////////////////////////// Delay in secs : " +
str(ks))
if (firstRun):
ks = datetime.now().second
print("First Run - Sleeping for " + str(60 - ks) + " secs.")
firstRun = False
time.sleep(60 - ks)
else:
print("Subsequent runs ...")
ks = datetime.now().second
#print("=>S===> / ks = " + str(ks))
for x in range(20):
p = Process(target=f,))
p.start()
ks = datetime.now().second
#print("=>E===> ks = " + str(ks))
p.join()
print("Will sleep for " + str(60 - ks) + " secs.")
time.sleep(60 - ks)
输出:
//////////////////////////////////////////// Delay in secs : 6
Subsequent runs ...
Starting process : 2
Starting process : 0
Starting process : 1
Starting process : 3
Starting process : 5
Starting process : 4
Starting process : 14
Starting process : 9
Starting process : 15
Starting process : 11
Starting process : 17
Starting process : 6
Starting process : 8
Starting process : 12
Starting process : 18
Starting process : 16
Starting process : 13
Starting process : 10
Starting process : 19
Starting process : 7
Ending process : 2
Ending process : 0
Ending process : 1
Ending process : 3
Ending process : 5
Ending process : 4
Ending process : 14
Ending process : 9
Ending process : 15
Ending process : 11
Ending process : 17
Ending process : 6
Ending process : 12
Ending process : 8
Ending process : 18
Ending process : 16
Ending process : 13
Ending process : 10
Ending process : 19
Ending process : 7
Will sleep for 54 secs.
解决方法
使用“计划”库解决了该问题:
import schedule
.
.
.
schedule.every(1).minutes.at(":00").do(run_threaded,job)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。