0mq:发布订阅延迟随消息不断增长?
pub.py
import zmq
import random
import sys
import time
port = "5556"
if len(sys.argv) > 1:
port = sys.argv[1]
int(port)
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:%s" % port)
topic = 10001
while True:
msgdata = time.time()
socket.send("%d %d" % (topic, msgdata))
print "topic:%d, msg:%.5f" % (topic, msgdata)
time.sleep(1)
sub.py
import sys
import zmq
import time
port = "5556"
if len(sys.argv) > 1:
port = sys.argv[1]
int(port)
if len(sys.argv) > 2:
port1 = sys.argv[2]
int(port1)
# Socket to talk to server
context = zmq.Context()
socket = context.socket(zmq.SUB)
print 'connecting to publisher'
socket.connect ("tcp://localhost:%s" % port)
if len(sys.argv) > 2:
socket.connect ("tcp://localhost:%s" % port1)
topicfilter = "10001"
socket.setsockopt(zmq.SUBSCRIBE, topicfilter)
total_value = 0
while True:
string = socket.recv()
got_time = time.time()
topic, msgdata = string.split()
dur = got_time - float(msgdata)
print 'it took %.5f from pub' % dur
输出结果
connecting to publisher
it took 0.11123 from pub
it took 0.11221 from pub
it took 0.11322 from pub
it took 0.11421 from pub
it took 0.11524 from pub
it took 0.11622 from pub
it took 0.11729 from pub
it took 0.11830 from pub
it took 0.11921 from pub
it took 0.12022 from pub
it took 0.12120 from pub
it took 0.12223 from pub
it took 0.12322 from pub
it took 0.12428 from pub
it took 0.12521 from pub
it took 0.12630 from pub
it took 0.12722 from pub
it took 0.12822 from pub
it took 0.12922 from pub
it took 0.13022 from pub
it took 0.13123 from pub
it took 0.13223 from pub
it took 0.13324 from pub
it took 0.13422 from pub
it took 0.13530 from pub
it took 0.13622 from pub
it took 0.13722 from pub
it took 0.13821 from pub
it took 0.13934 from pub
it took 0.14022 from pub
it took 0.14122 from pub
it took 0.14224 from pub
it took 0.14321 from pub
it took 0.14428 from pub
it took 0.14522 from pub
it took 0.14624 from pub
it took 0.14731 from pub
it took 0.14823 from pub
it took 0.14922 from pub
it took 0.15028 from pub
it took 0.15127 from pub
it took 0.15220 from pub
it took 0.15321 from pub
it took 0.15421 from pub
it took 0.15532 from pub
it took 0.15632 from pub
it took 0.15723 from pub
it took 0.15823 from pub
- 为什么延迟一直在增加?
- 我以为根据 http://zeromq.org/results:more-precise-0mq-tests 的说法,ZMQ的延迟应该更低?
- 我该怎么做才能降低延迟?
1 个回答
3
问题出在计算上。
pub.py 发送的时间戳是一个整数:
socket.send("%d %d" % (topic, msgdata))
把它换成:
socket.send("%d %.5f" % (topic, msgdata))
通过这个修改,延迟几乎保持在0.00030秒。