Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 541
Matt Seymour Avatar asked Jan 27 '26 23:01

Matt Seymour


1 Answers

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).

like image 134
Martijn Pieters Avatar answered Jan 30 '26 13:01

Martijn Pieters