faqts : Computers : Programming : Languages : Python : Common Problems

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

5 of 5 people (100%) answered Yes
Recently 4 of 4 people (100%) answered Yes

Entry

How do I get those nicely formatted values that these programs show which indicate total and current bandwidth?

Aug 12th, 2000 17:35
unknown unknown, Mike Fletcher


Here's the results of running the module in test mode:
p:\>p:\downloadprofiler.py
2.0 B/s total
2.0 B/s instant
257.2 B/s total
511.3 B/s instant
854.0 B/s total
2.0 KB/s instant
512.4 KB/s total
2.0 MB/s instant
409.8 MB/s total
2.0 GB/s instant
341.4 GB/s total
2.0 TB/s instant
Enjoy all, (this is largely untested, use at your own risk),
Mike
8<________ downloadprofiler.py _______
import time
KILOBYTES = 1024.0
MEGABYTES = KILOBYTES*1024
GIGABYTES = MEGABYTES*1024
TERABYTES = GIGABYTES*1024
SMALLTIME = 0.000000001
class DowloadProfiler:
        displayTemplates = [
                (TERABYTES, '%0.1f TB/s'), # ah, to have a 
terabyte/second
network connection :)
                (GIGABYTES, '%0.1f GB/s'),
                (MEGABYTES, '%0.1f MB/s'),
                (KILOBYTES, '%0.1f KB/s'),
                (0, '%0.1f B/s'),
        ]
        def __init__( self ):
                self.received = 0L
        def start( self ):
                self.starttime = time.clock()
                self.previoustime = self.starttime
                self.instantaneous = 0
        def more( self, amount ):
                self.received = self.received + amount
                self.instantaneous = amount/ ((time.clock() -
self.previoustime) or SMALLTIME)
                self.previoustime = time.clock()
        def displayTotal( self ):
                return self._display( self.received/
((time.clock()-self.starttime) or SMALLTIME) )
        def displayInstant( self ):
                return self._display( self.instantaneous )
        def _display( self, amount ):
                for threshold, template in self.displayTemplates:
                        if amount > threshold:
                                if threshold:
                                        amount = amount/threshold
                                return template % amount
def test():
        d = DowloadProfiler()
        d.start()
        for data in (2, 512, 2*KILOBYTES, 2*MEGABYTES, 2*GIGABYTES,
2*TERABYTES ):
                time.sleep( 1)
                d.more( data )
                print d.displayTotal(), 'total'
                print d.displayInstant(), 'instant'
if __name__ == "__main__":
        test()