使用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()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏