【发布时间】:2020-03-10 10:44:41
【问题描述】:
我目前正在解析瑞典公共交通网络的历史延误数据。从 1 月 27 日开始,我有大约 5700 个文件(每 15 秒一个),其中包含网络中正在运行的车辆的瞬时延迟数据。不幸的是,这是很多开销/重复数据,所以我想解析出相关的东西来对其进行可视化。
但是,当我尝试使用下面的脚本解析和过滤掉行程级别的相关延迟数据时,它的执行速度非常慢。它现在已经运行了超过 1.5 小时(在我的 2019 Macbook Pro 15' 上)并且还没有完成。
- 如何优化/改进这个 python 解析器?
- 或者我应该减少此任务的文件数量,即数据收集频率?
提前非常感谢您。 ????
from google.transit import gtfs_realtime_pb2
import gzip
import os
import datetime
import csv
import numpy as np
directory = '../data/tripu/27/'
datapoints = np.zeros((0,3), int)
read_trips = set()
# Loop through all files in directory
for filename in os.listdir(directory)[::3]:
try:
# Uncompress and parse protobuff-file using gtfs_realtime_pb2
with gzip.open(directory + filename, 'rb') as file:
response = file.read()
feed = gtfs_realtime_pb2.FeedMessage()
feed.ParseFromString(response)
print("Filename: " + filename, "Total entities: " + str(len(feed.entity)))
for trip in feed.entity:
if trip.trip_update.trip.trip_id not in read_trips:
try:
if len(trip.trip_update.stop_time_update) == len(stopsOnTrip[trip.trip_update.trip.trip_id]):
print("\t","Adding delays for",len(trip.trip_update.stop_time_update),"stops, on trip_id",trip.trip_update.trip.trip_id)
for i, stop_time_update in enumerate(trip.trip_update.stop_time_update[:-1]):
# Store the delay data point (arrival difference of two ascending nodes)
delay = int(trip.trip_update.stop_time_update[i+1].arrival.delay-trip.trip_update.stop_time_update[i].arrival.delay)
# Store contextual metadata (timestamp and edgeID) for the unique delay data point
ts = int(trip.trip_update.stop_time_update[i+1].arrival.time)
key = int(str(trip.trip_update.stop_time_update[i].stop_id) + str(trip.trip_update.stop_time_update[i+1].stop_id))
# Append data to numpy array
datapoints = np.append(datapoints, np.array([[key,ts,delay]]), axis=0)
read_trips.add(trip.trip_update.trip.trip_id)
except KeyError:
continue
else:
continue
except OSError:
continue
【问题讨论】:
-
很难说,我强烈怀疑大部分时间都花在了
ParseFromString,但无法仅从这段代码中知道。此外,readTrips永远不会更新,因此您的"if ... not in readTrips:"代码没有任何帮助。 (可能还想让read_trips成为一个集合而不是一个列表以进行更优化的搜索,但我 99-44/100% 确定这不是您的性能瓶颈所在。)为了获得更好的响应,请发布一个小样本数据文件,以及ParseFromString的代码。加上实际的分析也会很好。 -
@PaulMcG 感谢您的回复!我的错,我现在将 read_trip 添加为一组。上面编辑。看起来脚本现在开始时读取数据的速度非常快,然后速度变慢了很多。这有什么具体的线索吗? ParseFromString 来自google.transit。我也会上传一些数据。
-
数据总大小是多少,可用内存是多少?
标签: python numpy parsing data-science gtfs