python學習 —— 多線程發送請求測試伺服器壓力

來源:互聯網
上載者:User

標籤:學習   ext   oca   random   odi   多少   ini   daemon   long   

  以前寫過的python多線程終於派上用場了,其實還沒開始測試,但下周會使用這個指令碼測試一下,雖然boss讓我用C++來做:

# coding=utf-8import randomimport stringimport threadingimport timefrom requests import postclass MultiThread(threading.Thread):    def __init__(self, url, qlock):        threading.Thread.__init__(self)        self.url = url        self.qlock = qlock    def run(self):        send_requests(self.url, self.qlock)def send_requests(url, qlock):    """    :param url: http://xxx    :param qlock: 線程鎖    :return:    """    qlock.acquire()    nums = ‘0123456789‘    try:        json = {            ‘longitude‘: ‘‘.join(random.sample(nums + string.digits, 3)) + ‘.‘ + ‘‘.join(random.sample(nums + string.digits, 10)),            ‘latitude‘: ‘‘.join(random.sample(nums + string.digits, 2)) + ‘.‘ + ‘‘.join(random.sample(nums + string.digits, 10)),            ‘subTime‘: time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime()),            ‘machineId‘: ‘‘.join(random.sample(string.ascii_letters + string.digits, 6))        }        r = post(url, json=json, timeout=1)        print r.status_code        # print r.text    finally:        qlock.release()def run_thread(url, concurrency):    """    :param url: http://xxx    :param concurrency: 並發數    :return:    """    lock = threading.Lock()    threads = []    for cncu in range(1, concurrency):        t = MultiThread(url, lock)        t.daemon = True        t.start()        threads.append(t)    for t in threads:        t.join()if __name__ == ‘__main__‘:    url = ‘http://xxx‘    for i in range(0, 1000000):        run_thread(url, 10)

  其實我不太明白如果用C++來做在做壓力測試會更好嗎?雖然眾所周知python的多線程是假的(GIL鎖),不管開了多少個線程,實際上也只有1個線程在跑。。。C++多線程當然效能更好,但我個人總覺得做壓力測試貌似用不上C++?

  個人對這兩門語言的認識是這樣的:python是解釋型語言,所以每次運行都需要解譯器邊解釋邊運行(我記得python為瞭解決這個問題 --- 提高效能,所以會產生一些設定檔,如果代碼沒有改動,那麼就按上次啟動並執行過程執行 --- 貌似是這樣 = =);而C/C++通過編譯器產生的可執行檔在運行時可能會需要調用一些動態連結程式庫(dll),但不需要每次運行都編譯一遍,所以效能上是優秀的。

  這一塊完全是自己的知識盲區(學習深度還是不夠),如果有很懂的同學,還望能不吝教指!

  

python學習 —— 多線程發送請求測試伺服器壓力

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.