Matt Seymour
Matt Seymour

Reputation: 9395

Python timing a socket connection

I am looking to get the time taken to complete a round trip to a server using TCP. When using a windows client. (I would use ping but the server is blocking this)

I am looking at using python and sockets to complete this and I currently have.

import time
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM )

start = time.time()
s.connect(('localhost',80))
print 'time taken ', time.time()-start ,' seconds'

s.close()

The issue I have is I do not think the connection timer is working as I am regularly getting the same time stamp returned. Could someone point me in the right direction to sorting out this issue.

Upvotes: 3

Views: 8993

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121316

On Windows, the time.time() value does not have enough granularity (only 1/60th of a second). Use time.perf_counter() which on Windows has about 1/3rd of a microsecond resolution, instead:

start = time.perf_counter()
s.connect(('localhost',80))
print 'time taken ', time.perf_counter()-start ,' seconds'

This is the same timer that the timeit module uses; you could use the .default_timer() definition instead:

import timeit

start = timeit.default_timer()
# etc.

This also works on Python 2, where time.perf_counter() is not available, but timeit.default_timer() will reference the best-available timer for your OS (time.clock() on Windows, which there has about 1/100th of a second resolution, time.time() on other systems).

Upvotes: 7

halex
halex

Reputation: 16403

With the following modified script I get the same results as ping on Windows 7.

import time
import socket
while True:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM )
    start = time.time()
    s.connect(('www.google.at',80))
    print 'time taken ', (time.time()-start)*1000 ,' ms'
    s.close()
    time.sleep(1)

Pinging my localhost always gives me the same very small value. This could be the problem.

Upvotes: 2

Related Questions