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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With