Search code examples
pythonsystem

Am trying to determent the time/latency from os.system('ping') function on python


import os import time for i in range(20): start = time.time() os.system('ping -n 1 {}'.format('google.com')) end = time.time() I tried this one but i the end - start is not efficient so am trying to get a solution on how to get the time from the commend


Solution

  • try this:

     def TicTocGenerator():
            # Generator that returns time differences
            ti = 0  # initial time
            tf = time.time()  # final time
            while True:
                ti = tf
                tf = time.time()
                yield tf - ti  # returns the time difference
    
    
        TicToc = TicTocGenerator()  # create an instance of the TicTocGen generator
    
        def toc(tempBool=True):
            # Prints the time difference yielded by generator instance TicToc
            tempTimeInterval = next(TicToc)
            if tempBool:
                print("Elapsed time: %f seconds.\n" % tempTimeInterval)
        
        
        def tic():
            # Records a time in TicToc, marks the beginning of a time interval
            toc(False)
        
        
        
        
        tic()
        #your code here
        toc()
    

    but if you need ping statistics you can use:

    from pythonping import ping
    
    PingRes = ping(target=self.ip,timeout=3,count=3, verbose=True)