Python 有点慢.我怎样才能加速这个代码? [英] Python is a bit slow. How can I speed up this code?

查看:55
本文介绍了Python 有点慢.我怎样才能加速这个代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 令我失望.我搜索了端口扫描的代码,找到了这个.跑了它.我用来扫描的程序.根据python代码,它非常快.代码如下.
你能帮我加速我的代码吗?我能为它做什么?.

Python is disappointing me. I searched a code for port scan, found this. Runned it. the program I used for scanning. It was very fast according to python code. the code is below.
Can you help me about accelerating my code. What can i du for it?.

#!/usr/bin/env python  
from socket import *   

if __name__ == '__main__':  
    target = raw_input('Enter host to scan: ')  
    targetIP = gethostbyname(target)  
    print 'Starting scan on host ', targetIP  

    #scan reserved ports  
    for i in range(20, 1025):  
        s = socket(AF_INET, SOCK_STREAM)  

        result = s.connect_ex((targetIP, i))  

        if(result == 0) :  
            print 'Port %d: OPEN' % (i,)  
        s.close()

推荐答案

您正在一个接一个地打开一千个连接.这必须至少是到服务器的往返时间的 1000 倍.Python与它无关,这只是网络的一个非常基本的事实.

You are opening a thousand connections one after another. This has to take at least 1000 times the round trip time to the server. Python has nothing to do with it, this is just a very basic fact of networks.

为了加快速度,您可以使用线程或基于事件的框架(如扭曲)并行打开连接.

What you can do to speed this up is opening the connections in parallel, using threading or a event based framework like twisted.

这篇关于Python 有点慢.我怎样才能加速这个代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆