fork download
  1. import ipaddress
  2. import socket
  3. import struct
  4. import timeit
  5.  
  6. iterations = int(1e4)
  7.  
  8. benchmark = timeit.timeit("""
  9. n = ipaddress.ip_network('127.0.0.0/8')
  10. """, number=iterations, globals=globals())
  11. time1 = timeit.timeit("""
  12. ipstr = str(ipaddress.ip_network('127.0.0.0/8').network_address)
  13. parts = ipstr.split('.')
  14. (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
  15. """, number=iterations, globals=globals())
  16. time1str = timeit.timeit("""
  17. ipstr = '127.0.0.0'
  18. parts = ipstr.split('.')
  19. (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
  20. """, number=iterations, globals=globals())
  21. time2 = timeit.timeit("""
  22. struct.unpack("!L", socket.inet_aton(str(ipaddress.ip_network('127.0.0.0/8').network_address)))[0] >> 24
  23. """, number=iterations, globals=globals())
  24. time2str = timeit.timeit("""
  25. struct.unpack("!L", socket.inet_aton('127.0.0.0'))[0] >> 24
  26. """, number=iterations, globals=globals())
  27. time3 = timeit.timeit("""
  28. int.from_bytes(map(int, str(ipaddress.ip_network('127.0.0.0/8').network_address).split('.')), 'big') >> 24
  29. """, number=iterations, globals=globals())
  30. time3str = timeit.timeit("""
  31. int.from_bytes(map(int, '127.0.0.0'.split('.')), 'big') >> 24
  32. """, number=iterations, globals=globals())
  33. time4 = timeit.timeit("""
  34. int(ipaddress.ip_network('127.0.0.0/8').network_address) >> 24
  35. """, number=iterations, globals=globals())
  36.  
  37.  
  38. print("{:.4f} - Benchmark (time it takes to generate the ipaddress network object)".format(benchmark))
  39. print()
  40. print("{:.4f} - Manually conversion (without ipaddress {:.4f})".format(time1, time1str))
  41. print("{:.4f} - socket & struct (without ipaddress {:.4f})".format(time2, time2str))
  42. print("{:.4f} - int.from_bytes([<ip segments>]) (without ipaddress {:.4f})".format(time3, time3str))
  43. print("{:.4f} - int(<ipaddress address object>)".format(time4))
  44. print()
  45. print("""
  46. Conclusion:
  47. If you are using the ipaddress module, the IP int is precaculated which
  48. makes it the fastest. Otherwise, use the socket/struct method.
  49. """)
Success #stdin #stdout 0.53s 28872KB
stdin
Standard input is empty
stdout
0.0799 - Benchmark (time it takes to generate the ipaddress network object)

0.1095 - Manually conversion (without ipaddress 0.0096)
0.1037 - socket & struct (without ipaddress 0.0035)
0.1096 - int.from_bytes([<ip segments>]) (without ipaddress 0.0106)
0.0835 - int(<ipaddress address object>)


Conclusion:
    If you are using the ipaddress module, the IP int is precaculated which
    makes it the fastest.  Otherwise, use the socket/struct method.