Python gps阅读器消耗100%的CPU

时间:2014-07-26 19:23:32

标签: python gps multiprocessing

我还没有找到任何与Python GPS Module: Reading latest GPS Data类似的gpsd示例。使用多处理我编写了一个处理从设备读取gps数据的Process,其中包含以下run()。注意,我希望能够停止这个过程,所以我不能只使用gps会话的next()函数,因为它是一个阻塞调用:

# connect to gpsd
g = gps.gps('127.0.0.1',2947)
g.stream(gps.WATCH_ENABLE)

while True:
    try:
         if poisonpillq.get_nowait() == '!STOP!': break
    except Queue.Empty:
        if g.waiting():
            rpt = g.next()
            if rpt['class'] == 'TPV':
                --- store_gps_data from rpt/g ---

这样做,我的CPU达到了100%。使用程序xpgs测试CPU使用率,CPU的最大使用率为15%。那么如何规避这种用法呢?

1 个答案:

答案 0 :(得分:0)

添加“轮询”时间会减少使用量。像这样:

# connect to gpsd
g = gps.gps('127.0.0.1',2947)
g.stream(gps.WATCH_ENABLE)

while True:
    try:
         if poisonpillq.get(True,polltime) == '!STOP!': break
    except Queue.Empty:
        while g.waiting():
            rpt = g.next()
            if rpt['class'] == 'TPV':
                --- store_gps_data from rpt/g ---

如果轮询时间为0.5,则CPU使用率不会超过20%。轮询时间为3.0,CPU使用率最高可达17%左右。

这不是一个完美的解决方案。由于gps传输是串行的,因此进程阻塞毒丸队列的时间越长,需要读取的数据就越多,这意味着调用者可能需要等待很长时间才能获得gps进程获得毒丸。此外,是否有可能始终存在数据并且gps进程永远不会获得毒丸队列?