压力测试Demo

from concurrent.futures import ThreadPoolExecutor
import threading
import time

#全局变量
var = 1
#线程私有变量
local = threading.local();

def func():
    #计数器
    count = 0
    #每个线程跑100次用例
    for i in range(100):
        local.x = var
        if testa() and testb() and testc() :
            #计数成功用例
            count = count + 1
    print('线程私有变量:{}'.format(local.x))
    time.sleep(1)
    #返回每个线程成功用例个数
    return count

def testa():
    #用例a修改线程私有变量
    local.x = local.x + 1
    #用例流程 返回用例结果
    return True

def testb():
    # 用例b修改线程私有变量
    local.x = local.x + 2
    # 用例流程 返回用例结果
    return True

def testc():
    # 用例c修改线程私有变量
    local.x = local.x + 3
    # 用例流程 返回用例结果
    return True

if __name__ == '__main__':
    t = ThreadPoolExecutor(max_workers=20)  # 创建size为20的线程池,最好不要超过CPU核数的5倍

    tasks = [] # 线程任务
    results = [] #用于存放任务结构

    for i in range(20):
        tasks.append(t.submit(func)) # 将任务提交到线程池执行
    print('任务提交完毕')

    for i in range(len(tasks)):
        results.append(tasks[i].result())  # 获取任务返回结果

    t.shutdown()  # 相当于close() + join()

    print(results)

    print('主线程运行结束……')
线程私有变量:7
线程私有变量:7
线程私有变量:7
线程私有变量:7
线程私有变量:7
线程私有变量:7
线程私有变量:7
线程私有变量:7
线程私有变量:7
线程私有变量:7
线程私有变量:7
线程私有变量:7
线程私有变量:7
线程私有变量:7
线程私有变量:7
线程私有变量:7
线程私有变量:7
线程私有变量:7
线程私有变量:7
线程私有变量:7任务提交完毕

[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
主线程运行结束……
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值