使用Python对CPU进行压测

背景:测试ECS实例弹性伸缩功能,使用单一业务指标达不到压测效果,使用单独脚本对CPU进行压力测试

基于centos自带的python2版本进行压力测试

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import threading
import multiprocessing
import time
import signal
import sys
def cpu_bound_task():
"""执行一个无限循环的计算任务"""
while True:
# 简单的数学运算以消耗 CPU 资源
x = 0
for i in range(1000000):
x += i ** 2
def start_stress_test(num_threads=None):
"""启动指定数量的线程来执行 CPU 密集型任务"""
if num_threads is None:
num_threads = multiprocessing.cpu_count() # 默认使用所有可用的核心数
threads = []
print "Starting stress test with %d threads..." % num_threads
for _ in range(num_threads):
t = threading.Thread(target=cpu_bound_task)
t.daemon = True # 设置为守护线程,主线程结束时自动退出
t.start()
threads.append(t)
try:
while True:
time.sleep(1) # 主线程保持运行状态
except KeyboardInterrupt:
print "\nStopping stress test..."
sys.exit(0)
if __name__ == "__main__":
# 捕获 Ctrl+C 信号以优雅地退出
signal.signal(signal.SIGINT, signal.default_int_handler)
# 启动 CPU 压力测试,默认使用所有核心
start_stress_test()
posted @   帅帅啊  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示