1. 程式人生 > >python學習 —— 多線程發送請求測試服務器壓力

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

def [] clas init 並發數 ase 動態鏈接庫 服務器壓力 gil

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

# coding=utf-8
import random
import string
import threading
import time
from requests import post


class 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學習 —— 多線程發送請求測試服務器壓力