Measuring latencies from a Google server using subprocess

Viewed 27

The goal is to write a script that measures the response time of a Google server to the ping command and plots the results as a histogram.

So far this is my code for obtaining a 10 ping latency dataset:

import subprocess
from subprocess import check_output, Popen, call, PIPE, STDOUT

latency  = []
p = Popen('ping -n 10 google.com', stdout = PIPE, stderr = STDOUT, shell = True)
for line in p.stdout:
    lntxt = line.decode('utf-8').rstrip()
    words = lntxt.split(' ')
    if words[0] == 'Reply':
        print(words[4])
        latency.append(words[4])
        
print(latency)

Using this the output should be something like this:

[5, 13, 12, 11, 9, 11, 11, 4, 12, 10]

Then i would like to plot the latencies. I would appreciate any help with the plotting part.

Thanks in advance.

1 Answers

Update: Refined the latency capture and added code to plot the results as a histogram.

import re
import subprocess

import matplotlib.pyplot as plt

n = 10  # Number of pings to run

""" Start ny pinging a Google name server and recording the ping
    latency in list "latency"
"""
latency  = []
#  Run the ping command in a subprocess
p = subprocess.run(['ping', '-n', str(n), '8.8.8.8'],
     capture_output=True, text=True)
# Split the response into lines
for line in p.stdout.split('\n'):
    # Detect and parse lines that start with "Reply"
    m = re.search('Reply.*time=(.*)ms', line )
    if m:
        # Remember the latency time.
        latency.append(int(m[1]))

print("latency", latency)


""" Now plot the result as a histogram
"""

# Create list "bins" like [... 5.5, 6.5, 7.5 ...]
xmin = min(latency)
xmax = max(latency)
bins = [x-.5 for x in range(xmin, xmax+2)]
print("bins:", bins)

# Create the gistogram
plt.hist(latency, bins)

# Find out the range of the y axis. The min will
# be 0 but the max will depend on the data
ax = plt.gca()
ymin, ymax = ax.get_ylim()
print(ymin, ymax)

# Set the x and y tick ranges
plt.xticks(range(xmin,xmax+2))
plt.yticks(range(int(ymin),int(ymax+1)))

# Finally add a title and x, y axis labels
plt.title('Google Ping Latency in Milliseconds')
plt.xlabel('Time (ms)')
plt.ylabel('Count')

plt.show()

Output:

latency [5, 6, 6, 6, 9, 9, 9, 12, 5, 14]
bins: [4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5]
ymin, ymax: 0.0 3.15

The plot: Latency plot

Related