1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
from socket import * import threading import time
HOST = "122.51.252.101" PORT = 7474 thread_number = 1000 BUF_SIZE = 1024 Address = (HOST, PORT) message = "hello" tcp_connect_data = [] threadLock = threading.Lock()
def get_time_ms(): ct = time.time() local_time = time.localtime(ct) cart_time_strftime = time.strftime("%Y-%m-%d %H:%M:%S", local_time) cart_time_strftime_ms = (ct - int(ct)) * 1000 ms = "%s.%03d" % (cart_time_strftime, cart_time_strftime_ms) return ms, ct
def tcp_connect(): error_flag = 0 tcp_socket = socket(AF_INET, SOCK_STREAM) tcp_socket.settimeout(20) time1 = get_time_ms()
try: tcp_socket.connect(Address) """ receive_data = tcp_socket.recv(BUF_SIZE) # print(receive_data.decode('utf-8')) tcp_socket.send(message.encode('utf-8')) """ except Exception as e: error_flag = 1 print("tcpConnError", e) else: pass time2 = get_time_ms() delay_time = (time2[1] - time1[1])*1000 data = delay_time, error_flag tcp_connect_data.append(data) return data
class MyThread(threading.Thread):
def __init__(self, thread_id): threading.Thread.__init__(self) self.threadId = thread_id
def run(self): threadLock.acquire() tcp_connect() threadLock.release()
def info(self): print(self.threadId)
def locust(): test_thread = MyThread(0) test_thread.start() test_thread.join() delay_time_max = tcp_connect_data[test_thread.threadId][0] delay_time_min = delay_time_max error_times, success_times, total_time = 0, 0, 0 threads = [] data = [] for i in range(1, thread_number+1): t = MyThread(i) threads.append(t) for t in threads: t.start() t.join() delay_time = tcp_connect_data[t.threadId][0] error_flag = tcp_connect_data[t.threadId][1] if delay_time_max < delay_time: delay_time_max = delay_time if delay_time_min > delay_time: delay_time_min = delay_time total_time += delay_time delay_time_average = total_time/t.threadId error_times += error_flag success_times = t.threadId - error_times print("%s 执行时间为 %s\n" % (t, get_time_ms()[0])) print("平均往返时延(ms): %s 本次时延: %s 最大时延: %s 最小时延: %s 拒绝连接次数: %s 成功连接数: %s\n" % (delay_time_average, delay_time, delay_time_max, delay_time_min, error_times, success_times)) thread_data = (delay_time_average, delay_time, delay_time_max, delay_time_min, error_times, success_times), t data.append(thread_data) return data
if __name__ == '__main__': locust()
|