cpu使用率较高同时不断监听接收tcp 数据和发送数据
- User
cpu使用率较高同时不断监听接收tcp 数据和发送数据
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
cpu使用率较高同时不断监听接收tcp 数据和发送数据
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
对于需要同时处理高CPU计算和TCP网络通信的场景,我建议采用混合架构模式,将网络I/O与CPU计算分离处理。这样可以在保持网络响应性的同时,有效管理CPU资源。
import asyncio
import multiprocessing as mp
from concurrent.futures import ProcessPoolExecutor
import socket
import pickle
import time
# 共享队列,用于进程间通信
task_queue = mp.Queue() # 网络数据 -> 计算进程
result_queue = mp.Queue() # 计算结果 -> 网络发送
def cpu_worker(task_queue, result_queue):
"""CPU密集型计算进程"""
while True:
try:
# 非阻塞方式获取任务
try:
data = task_queue.get(block=False)
except:
time.sleep(0.001) # 短暂休眠避免CPU空转
continue
# 执行CPU密集计算
# 示例:假设我们需要处理一些数值计算
result = process_data(data)
# 将结果放入结果队列
result_queue.put(result)
except Exception as e:
print(f"Worker error: {e}")
def process_data(data):
"""CPU密集型数据处理函数"""
# 这里是你的实际计算逻辑
# 示例:计算密集型操作
processed = sum(i*i for i in range(1000000)) # 模拟计算
return {"original": data, "result": processed}
async def handle_client(reader, writer):
"""处理单个TCP客户端连接"""
addr = writer.get_extra_info('peername')
print(f"Connected: {addr}")
try:
while True:
# 异步读取数据
data = await reader.read(4096)
if not data:
break
# 将数据放入任务队列
task_queue.put(data)
# 检查是否有结果可发送
try:
if not result_queue.empty():
result = result_queue.get(block=False)
# 异步发送结果
writer.write(pickle.dumps(result))
await writer.drain()
except Exception as e:
print(f"Result handling error: {e}")
# 短暂休眠,避免过度消耗CPU
await asyncio.sleep(0.001)
except Exception as e:
print(f"Client error: {e}")
finally:
writer.close()
await writer.wait_closed()
print(f"Disconnected: {addr}")
async def tcp_server():
"""异步TCP服务器"""
server = await asyncio.start_server(
handle_client, '0.0.0.0', 8888
)
addr = server.sockets[0].getsockname()
print(f'Serving on {addr}')
async with server:
await server.serve_forever()
def main():
# 启动CPU工作进程池
num_workers = mp.cpu_count() - 1 # 保留一个核心给网络I/O
workers = []
for _ in range(num_workers):
p = mp.Process(target=cpu_worker, args=(task_queue, result_queue))
p.daemon = True
p.start()
workers.append(p)
# 启动异步网络服务器
asyncio.run(tcp_server())
# 清理进程
for p in workers:
p.join()
if __name__ == "__main__":
main()
分离关注点:
资源控制:
CPU核心数-1,预留一个核心给网络I/O性能优化:
pickle进行数据序列化(或考虑更高效的msgpack/protobuf)负载均衡:
网络优化:
uvloop替代标准事件循环,提升异步性能:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
内存优化:
multiprocessing.shared_memory)监控与自适应:
容错处理:
这种架构能够有效平衡CPU使用率和网络响应性,适合需要同时处理高计算负载和TCP通信的应用场景。
python 如何使用cpu多核
Python 默认受全局解释器锁(GIL)限制,单线程无法利用多核 CPU。以下是几种有效使用多核的方法:
最直接的方法是使用多进程,每个进程有独立的 Python 解释器和内存空间:
import multiprocessing as mp
import os
def cpu_bound_task(n):
"""CPU密集型任务示例"""
return sum(i * i for i in range(n))
if __name__ == '__main__':
# 获取CPU核心数
num_cores = os.cpu_count()
print(f"系统有 {num_cores} 个CPU核心")
# 创建进程池
pool = mp.Pool(processes=num_cores)
# 并行执行任务
results = pool.map(cpu_bound_task, [10000000] * num_cores)
# 关闭进程池
pool.close()
pool.join()
print("所有任务完成")
更现代的接口,使用更简洁:
from concurrent.futures import ProcessPoolExecutor
import os
def cpu_bound_task(n):
return sum(i * i for i in range(n))
if __name__ == '__main__':
# 创建进程池执行器
with ProcessPoolExecutor(max_workers=os.cpu_count()) as executor:
# 提交多个任务
futures = [executor.submit(cpu_bound_task, 10000000) for _ in range(os.cpu_count())]
# 获取结果
for future in futures:
result = future.result()
print(f"任务结果: {result}")
Numba 可以将 Python 代码编译为机器码并释放 GIL:
import numba
import numpy as np
@numba.njit(parallel=True)
def parallel_sum(arr):
"""并行计算数组元素平方和"""
result = 0.0
# 使用并行循环
for i in numba.prange(len(arr)):
result += arr[i] ** 2
return result
# 创建大数组
data = np.arange(10000000)
# 执行并行计算
result = parallel_sum(data)
print(f"结果: {result}")
适合大规模数据处理:
import dask.array as da
import numpy as np
# 创建大型 Dask 数组
x = da.random.random((10000, 10000), chunks=(1000, 1000))
# 执行并行计算
result = x.mean().compute()
print(f"平均值: {result}")
科学计算中常用:
from joblib import Parallel, delayed
import os
def process_chunk(chunk):
return sum(i ** 2 for i in chunk)
# 准备数据
data = range(10000000)
# 分块
chunk_size = len(data) // os.cpu_count()
chunks = [data[i:i+chunk_size] for i in range(0, len(data), chunk_size)]
# 并行处理
results = Parallel(n_jobs=os.cpu_count())(
delayed(process_chunk)(chunk) for chunk in chunks
)
# 合并结果
final_result = sum(results)
print(f"最终结果: {final_result}")
对于复杂应用,可以组合使用多种并发模型:
import multiprocessing as mp
import asyncio
import os
async def io_task():
"""IO密集型任务"""
await asyncio.sleep(1)
return "IO任务完成"
def process_worker(worker_id):
"""每个进程运行一个事件循环处理多个IO任务"""
print(f"进程 {worker_id} 启动")
async def run_tasks():
tasks = [io_task() for _ in range(10)]
results = await asyncio.gather(*tasks)
return results
# 在进程中运行事件循环
results = asyncio.run(run_tasks())
return results
if __name__ == "__main__":
# 创建多个进程,每个进程处理多个异步任务
with mp.Pool(processes=os.cpu_count()) as pool:
all_results = pool.map(process_worker, range(os.cpu_count()))
print(f"所有进程完成,共处理 {len(all_results) * 10} 个任务")
混合型应用:多进程 + 异步IO 是不是每个进程开一个线程
不是的。混合型应用中的"多进程 + 异步IO"模式并不是每个进程开一个线程,而是每个进程运行一个事件循环来处理多个异步任务。这是一个重要的区别:
每个进程运行一个事件循环:
协程而非线程:
系统
├── 进程1 (使用CPU核心1)
│ └── 主线程
│ └── 事件循环
│ ├── 协程A (处理IO任务1)
│ ├── 协程B (处理IO任务2)
│ └── 协程C (处理IO任务3)
│
├── 进程2 (使用CPU核心2)
│ └── 主线程
│ └── 事件循环
│ ├── 协程D (处理IO任务4)
│ ├── 协程E (处理IO任务5)
│ └── 协程F (处理IO任务6)
...
import multiprocessing as mp
import asyncio
import time
import os
async def async_io_task(task_id):
"""模拟IO密集型任务"""
print(f"开始IO任务 {task_id}")
await asyncio.sleep(1) # 模拟IO操作(网络请求、文件读写等)
print(f"完成IO任务 {task_id}")
return task_id
def cpu_bound_work(x):
"""模拟CPU密集型计算"""
return sum(i*i for i in range(x))
async def mixed_task(task_id, cpu_work_size):
"""混合任务:既有IO又有CPU计算"""
# IO部分使用异步
await asyncio.sleep(0.5)
# CPU密集部分
result = cpu_bound_work(cpu_work_size)
# 再进行IO操作
await asyncio.sleep(0.5)
return f"任务{task_id}完成,计算结果: {result}"
def process_worker(process_id):
"""进程工作函数 - 每个进程只有一个线程,但处理多个异步任务"""
print(f"进程 {process_id} 启动 (PID: {os.getpid()})")
async def run_tasks_in_process():
# 创建多个异步任务
tasks = []
for i in range(5): # 每个进程处理5个任务
task_id = f"{process_id}-{i}"
tasks.append(mixed_task(task_id, 1000000))
# 并发执行所有任务
results = await asyncio.gather(*tasks)
return results
# 在当前进程中运行事件循环
start = time.time()
results = asyncio.run(run_tasks_in_process())
end = time.time()
print(f"进程 {process_id} 完成,耗时: {end-start:.2f}秒")
return results
if __name__ == "__main__":
num_processes = os.cpu_count()
print(f"系统有 {num_processes} 个CPU核心,启动相同数量的进程")
start_time = time.time()
# 创建并启动多个进程
with mp.Pool(processes=num_processes) as pool:
all_results = pool.map(process_worker, range(num_processes))
end_time = time.time()
# 统计结果
total_tasks = sum(len(results) for results in all_results)
print(f"所有进程完成,共处理 {total_tasks} 个任务,总耗时: {end_time-start_time:.2f}秒")
充分利用多核:每个进程可以占用一个CPU核心,绕过GIL限制
高效处理IO:每个进程内部使用异步IO,一个线程可以处理成百上千个IO任务
资源利用平衡:
扩展性好:可以根据服务器核心数和负载特性调整进程数量
这种模式特别适合既有计算又有IO的混合应用,如Web服务器、数据处理管道等。每个进程只有一个线程,但这个线程通过异步IO可以处理多个并发任务,比"每个进程一个线程"的模式效率高得多。
6核16G内存能跑多少协程
对于6核16GB内存的系统,协程数量主要受内存限制而非CPU核心数,因为协程是轻量级的并发单元。以下是具体分析:
内存因素:
实际限制因素:
根据应用类型,6核16GB系统的实际可行协程数:
轻量级网络服务(如简单API代理):
中等复杂度应用(如Web服务器):
数据处理应用(处理较大数据集):
对于6核16GB系统,建议的配置:
import asyncio
import multiprocessing as mp
import os
import psutil
import resource
def set_system_limits():
# 提高文件描述符限制(需要root权限)
soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
resource.setrlimit(resource.RLIMIT_NOFILE, (65535, hard))
print(f"文件描述符限制: {resource.getrlimit(resource.RLIMIT_NOFILE)}")
async def worker_task(task_id):
# 模拟协程工作
await asyncio.sleep(1)
return f"任务 {task_id} 完成"
async def run_many_tasks(num_tasks):
# 创建大量协程任务
tasks = [worker_task(i) for i in range(num_tasks)]
# 分批执行,避免一次创建过多任务对象
batch_size = 10000
results = []
for i in range(0, len(tasks), batch_size):
batch = tasks[i:i+batch_size]
batch_results = await asyncio.gather(*batch)
results.extend(batch_results)
# 打印内存使用情况
process = psutil.Process(os.getpid())
memory_use = process.memory_info().rss / 1024 / 1024 # MB
print(f"已完成 {i+len(batch)} 个任务,当前内存使用: {memory_use:.2f} MB")
return results
def process_worker(process_id, num_tasks_per_process):
"""每个进程运行一个事件循环处理多个协程"""
print(f"进程 {process_id} 启动")
return asyncio.run(run_many_tasks(num_tasks_per_process))
if __name__ == "__main__":
# 设置系统限制
try:
set_system_limits()
except:
print("无法设置系统限制,可能需要root权限")
# 系统配置
num_cores = 6 # 6核CPU
available_memory = 16 * 1024 # 16GB内存 (MB)
# 保守估计,为系统和其他进程预留内存
usable_memory = available_memory * 0.7 # 使用70%的内存
# 估算每个协程内存占用 (示例值,需根据实际应用调整)
memory_per_coroutine = 0.05 # 50KB/协程
# 计算可运行的协程总数
total_coroutines = int(usable_memory / memory_per_coroutine)
coroutines_per_process = total_coroutines // num_cores
print(f"系统配置: {num_cores}核, {available_memory}MB内存")
print(f"估计可运行协程总数: {total_coroutines}")
print(f"每个进程分配协程数: {coroutines_per_process}")
# 启动多进程
with mp.Pool(processes=num_cores) as pool:
args = [(i, coroutines_per_process) for i in range(num_cores)]
results = pool.starmap(process_worker, args)
print("所有任务完成")
WebSocket 推送?
WebSocket 是实现实时推送的理想协议,在 Python 中可以高效实现。以下是基于异步 IO 和多进程的 WebSocket 推送服务架构:
import asyncio
import websockets
import json
import time
import os
import multiprocessing as mp
from concurrent.futures import ProcessPoolExecutor
# 存储所有连接的客户端
connected_clients = set()
async def register_client(websocket):
"""注册新客户端连接"""
connected_clients.add(websocket)
print(f"新客户端连接,当前连接数: {len(connected_clients)}")
async def unregister_client(websocket):
"""注销客户端连接"""
connected_clients.remove(websocket)
print(f"客户端断开连接,当前连接数: {len(connected_clients)}")
async def websocket_handler(websocket, path):
"""处理WebSocket连接"""
await register_client(websocket)
try:
# 保持连接并接收消息
async for message in websocket:
# 这里可以处理客户端发来的消息
data = json.loads(message)
print(f"收到消息: {data}")
# 示例:回复确认消息
await websocket.send(json.dumps({"status": "received", "time": time.time()}))
except websockets.exceptions.ConnectionClosed:
print("连接异常关闭")
finally:
await unregister_client(websocket)
async def broadcast_message(message):
"""向所有连接的客户端广播消息"""
if not connected_clients:
return
# 并发发送消息给所有客户端
coroutines = [client.send(message) for client in connected_clients]
await asyncio.gather(*coroutines, return_exceptions=True)
async def periodic_push():
"""定期推送消息的协程"""
while True:
# 创建推送消息
message = json.dumps({
"type": "update",
"data": {
"timestamp": time.time(),
"value": os.urandom(4).hex() # 随机数据
}
})
# 广播消息
await broadcast_message(message)
print(f"已推送消息给 {len(connected_clients)} 个客户端")
# 等待下一次推送
await asyncio.sleep(5) # 每5秒推送一次
def cpu_intensive_task(data):
"""CPU密集型任务,在单独进程中执行"""
# 模拟复杂计算
result = sum(i*i for i in range(1000000))
return {"input": data, "result": result}
async def start_server(host, port):
"""启动WebSocket服务器"""
# 创建WebSocket服务器
server = await websockets.serve(
websocket_handler,
host,
port,
ping_interval=30, # 保持连接活跃
ping_timeout=10,
max_size=2**20, # 最大消息大小 1MB
max_queue=32 # 每个连接的消息队列大小
)
print(f"WebSocket服务器启动在 ws://{host}:{port}")
# 启动定期推送任务
asyncio.create_task(periodic_push())
# 保持服务器运行
await server.wait_closed()
async def main():
"""主异步函数"""
# 创建进程池用于CPU密集型任务
executor = ProcessPoolExecutor(max_workers=os.cpu_count())
# 启动WebSocket服务器
await start_server('0.0.0.0', 8765)
if __name__ == "__main__":
# 运行主异步函数
asyncio.run(main())
对于大规模推送服务,使用多进程 + Redis 实现更可靠的架构:
import asyncio
import websockets
import json
import time
import os
import redis.asyncio as redis
import multiprocessing as mp
import uvloop
# 使用uvloop加速异步IO
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
# Redis配置
REDIS_HOST = "localhost"
REDIS_PORT = 6379
REDIS_CHANNEL = "websocket_broadcast"
# 存储连接的客户端
connected_clients = set()
async def register_client(websocket):
"""注册新客户端连接"""
connected_clients.add(websocket)
print(f"新客户端连接,当前连接数: {len(connected_clients)}")
async def unregister_client(websocket):
"""注销客户端连接"""
connected_clients.remove(websocket)
print(f"客户端断开连接,当前连接数: {len(connected_clients)}")
async def websocket_handler(websocket, path):
"""处理WebSocket连接"""
client_id = os.urandom(4).hex()
await register_client(websocket)
try:
# 发送欢迎消息
await websocket.send(json.dumps({
"type": "welcome",
"client_id": client_id,
"time": time.time()
}))
# 保持连接并接收消息
async for message in websocket:
try:
data = json.loads(message)
print(f"客户端 {client_id} 发送: {data}")
# 回复确认消息
await websocket.send(json.dumps({
"type": "ack",
"time": time.time()
}))
except json.JSONDecodeError:
await websocket.send(json.dumps({
"type": "error",
"message": "Invalid JSON format"
}))
except websockets.exceptions.ConnectionClosed as e:
print(f"客户端 {client_id} 连接关闭: {e}")
finally:
await unregister_client(websocket)
async def redis_listener(redis_client):
"""监听Redis频道获取推送消息"""
# 订阅Redis频道
pubsub = redis_client.pubsub()
await pubsub.subscribe(REDIS_CHANNEL)
# 持续监听消息
async for message in pubsub.listen():
if message['type'] == 'message':
data = message['data'].decode('utf-8')
# 广播消息给所有客户端
await broadcast_message(data)
async def broadcast_message(message):
"""向所有连接的客户端广播消息"""
if not connected_clients:
return
# 创建发送任务
tasks = []
for client in connected_clients.copy(): # 使用副本避免迭代时修改
try:
tasks.append(asyncio.create_task(client.send(message)))
except websockets.exceptions.ConnectionClosed:
# 客户端已断开但未正确清理
if client in connected_clients:
connected_clients.remove(client)
# 等待所有发送完成
if tasks:
await asyncio.gather(*tasks, return_exceptions=True)
print(f"消息已推送给 {len(tasks)} 个客户端")
async def start_websocket_server(host, port):
"""启动WebSocket服务器"""
# 创建Redis连接
redis_client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, decode_responses=True)
# 启动Redis监听器
asyncio.create_task(redis_listener(redis_client))
# 启动WebSocket服务器
async with websockets.serve(
websocket_handler,
host,
port,
ping_interval=30,
ping_timeout=10,
max_size=2**20,
max_queue=64
):
print(f"WebSocket服务器启动在 ws://{host}:{port}")
# 保持服务器运行
await asyncio.Future() # 永久运行
def websocket_process(host, port):
"""WebSocket服务器进程"""
asyncio.run(start_websocket_server(host, port))
def publisher_process():
"""消息发布进程 - 生成推送内容"""
r = redis.Redis(host=REDIS_HOST, port=REDIS_PORT)
while True:
try:
# 创建推送消息
message = json.dumps({
"type": "update",
"data": {
"timestamp": time.time(),
"value": os.urandom(4).hex()
}
})
# 发布到Redis
r.publish(REDIS_CHANNEL, message)
print(f"消息已发布到Redis: {message[:30]}...")
# 等待下一次推送
time.sleep(5)
except Exception as e:
print(f"发布消息错误: {e}")
time.sleep(1)
if __name__ == "__main__":
# 启动多个WebSocket服务器进程
num_processes = max(1, os.cpu_count() - 1) # 保留一个核心给发布进程
processes = []
# 创建WebSocket服务器进程
for i in range(num_processes):
p = mp.Process(target=websocket_process, args=('0.0.0.0', 8765))
p.daemon = True
p.start()
processes.append(p)
print(f"WebSocket服务器进程 {i+1} 已启动")
# 创建发布进程
publisher = mp.Process(target=publisher_process)
publisher.daemon = True
publisher.start()
processes.append(publisher)
print("消息发布进程已启动")
# 等待所有进程
for p in processes:
p.join()
连接使用的时 reader, writer = await asyncio.open_connection(host, port)
如果你使用的是 asyncio.open_connection() 创建的 TCP 连接(而非 websockets 库),以下是基于原始 TCP 连接实现 WebSocket 推送服务的完整方案:
import asyncio
import json
import time
import os
import multiprocessing as mp
import struct
import base64
import hashlib
import re
from urllib.parse import parse_qs
# 存储所有连接的客户端
connected_clients = set()
async def handle_websocket_handshake(reader, writer):
"""处理WebSocket握手"""
# 读取HTTP请求头
http_request = b""
while True:
line = await reader.readline()
http_request += line
if line == b'\r\n' or not line:
break
# 解析HTTP请求
http_text = http_request.decode('utf-8')
# 检查是否是WebSocket升级请求
if "Upgrade: websocket" not in http_text:
writer.write(b"HTTP/1.1 400 Bad Request\r\n\r\nNot a WebSocket request")
await writer.drain()
writer.close()
return False
# 提取WebSocket密钥
key_match = re.search(r'Sec-WebSocket-Key: (.*)\r\n', http_text)
if not key_match:
writer.write(b"HTTP/1.1 400 Bad Request\r\n\r\nMissing WebSocket Key")
await writer.drain()
writer.close()
return False
websocket_key = key_match.group(1)
# 计算WebSocket接受密钥
magic_string = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
accept_key = base64.b64encode(
hashlib.sha1((websocket_key + magic_string).encode()).digest()
).decode()
# 发送WebSocket握手响应
response = (
"HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: {}\r\n\r\n"
).format(accept_key)
writer.write(response.encode())
await writer.drain()
return True
async def decode_websocket_frame(reader):
"""解码WebSocket帧"""
# 读取帧头部
try:
header = await reader.readexactly(2)
except asyncio.IncompleteReadError:
return None, None # 连接关闭
# 解析基本头部
fin = (header[0] & 0x80) != 0
opcode = header[0] & 0x0F
has_mask = (header[1] & 0x80) != 0
payload_length = header[1] & 0x7F
# 获取扩展长度
if payload_length == 126:
length_bytes = await reader.readexactly(2)
payload_length = struct.unpack("!H", length_bytes)[0]
elif payload_length == 127:
length_bytes = await reader.readexactly(8)
payload_length = struct.unpack("!Q", length_bytes)[0]
# 获取掩码
if has_mask:
mask = await reader.readexactly(4)
else:
mask = None
# 读取有效载荷
if payload_length > 0:
payload = await reader.readexactly(payload_length)
else:
payload = b""
# 解码有效载荷
if has_mask and mask:
payload = bytes(payload[i] ^ mask[i % 4] for i in range(len(payload)))
return opcode, payload
async def encode_websocket_frame(data, opcode=0x01):
"""编码WebSocket帧"""
if isinstance(data, str):
data = data.encode('utf-8')
# 创建帧头部
header = bytes([0x80 | opcode]) # FIN + opcode
# 添加长度
length = len(data)
if length < 126:
header += bytes([length])
elif length < 65536:
header += bytes([126]) + struct.pack("!H", length)
else:
header += bytes([127]) + struct.pack("!Q", length)
# 返回完整帧
return header + data
async def handle_client(reader, writer):
"""处理客户端连接"""
addr = writer.get_extra_info('peername')
print(f"新连接: {addr}")
# 执行WebSocket握手
if not await handle_websocket_handshake(reader, writer):
print(f"WebSocket握手失败: {addr}")
return
print(f"WebSocket握手成功: {addr}")
# 将客户端添加到连接列表
connected_clients.add(writer)
# 发送欢迎消息
welcome_msg = json.dumps({
"type": "welcome",
"client_id": addr[0] + ":" + str(addr[1]),
"time": time.time()
})
welcome_frame = await encode_websocket_frame(welcome_msg)
writer.write(welcome_frame)
await writer.drain()
try:
# 持续处理客户端消息
while True:
# 解码WebSocket帧
opcode, payload = await decode_websocket_frame(reader)
# 检查连接是否关闭
if opcode is None:
break
# 处理不同类型的帧
if opcode == 0x08: # 关闭帧
break
elif opcode == 0x09: # Ping帧
# 回复Pong
pong_frame = await encode_websocket_frame(b"", 0x0A)
writer.write(pong_frame)
await writer.drain()
elif opcode == 0x01 or opcode == 0x02: # 文本或二进制帧
if opcode == 0x01: # 文本帧
message = payload.decode('utf-8')
print(f"收到消息: {message}")
try:
# 尝试解析JSON
data = json.loads(message)
# 发送确认消息
response = json.dumps({
"type": "ack",
"time": time.time()
})
response_frame = await encode_websocket_frame(response)
writer.write(response_frame)
await writer.drain()
except json.JSONDecodeError:
# 非JSON消息
response = json.dumps({
"type": "error",
"message": "Invalid JSON format"
})
response_frame = await encode_websocket_frame(response)
writer.write(response_frame)
await writer.drain()
except (asyncio.CancelledError, ConnectionResetError, asyncio.IncompleteReadError) as e:
print(f"客户端连接异常: {addr} - {e}")
finally:
# 清理连接
if writer in connected_clients:
connected_clients.remove(writer)
writer.close()
await writer.wait_closed()
print(f"连接关闭: {addr}")
async def broadcast_message(message):
"""向所有连接的客户端广播消息"""
if not connected_clients:
return
# 编码WebSocket帧
if isinstance(message, dict):
message = json.dumps(message)
frame = await encode_websocket_frame(message)
# 并发发送消息
send_tasks = []
for writer in list(connected_clients):
try:
writer.write(frame)
send_tasks.append(writer.drain())
except Exception as e:
print(f"发送消息错误: {e}")
if writer in connected_clients:
connected_clients.remove(writer)
if send_tasks:
await asyncio.gather(*send_tasks, return_exceptions=True)
print(f"消息已推送给 {len(send_tasks)} 个客户端")
async def periodic_push():
"""定期推送消息"""
while True:
# 创建推送消息
message = {
"type": "update",
"data": {
"timestamp": time.time(),
"value": os.urandom(4).hex() # 随机数据
}
}
# 广播消息
await broadcast_message(message)
# 等待下一次推送
await asyncio.sleep(5) # 每5秒推送一次
async def start_server(host, port):
"""启动TCP服务器"""
server = await asyncio.start_server(
handle_client, host, port
)
addr = server.sockets[0].getsockname()
print(f'服务器启动在 {addr}')
# 启动定期推送任务
asyncio.create_task(periodic_push())
async with server:
await server.serve_forever()
def server_process(host, port):
"""服务器进程"""
asyncio.run(start_server(host, port))
if __name__ == "__main__":
# 启动多个服务器进程
num_processes = max(1, os.cpu_count() - 1) # 保留一个核心给系统
processes = []
host = '0.0.0.0'
port = 8765
for i in range(num_processes):
p = mp.Process(target=server_process, args=(host, port,))
p.daemon = True
p.start()
processes.append(p)
print(f"服务器进程 {i+1} 已启动")
# 等待所有进程
for p in processes:
p.join()
windows 系统python程序运行时如何查看那个部分占用内存最大
在Windows系统上查看Python程序内存占用情况,特别是找出占用内存最大的部分,可以使用以下几种方法:
tracemalloc模块Python 3.4+内置的tracemalloc模块可以跟踪Python对象的内存分配,找出内存占用最大的部分:
import tracemalloc
import time
# 启动内存跟踪
tracemalloc.start()
# 运行你的代码
# ...这里是你的主要代码...
# 获取当前内存快照
snapshot = tracemalloc.take_snapshot()
# 按行统计内存占用
top_stats = snapshot.statistics('lineno')
print("[ 内存占用前10大对象 ]")
for stat in top_stats[:10]:
print(stat)
# 按文件统计内存占用
print("\n[ 按文件统计内存占用 ]")
top_stats = snapshot.statistics('filename')
for stat in top_stats[:5]:
print(stat)
# 比较两个快照之间的内存差异
time.sleep(1) # 等待一段时间
snapshot2 = tracemalloc.take_snapshot()
top_stats = snapshot2.compare_to(snapshot, 'lineno')
print("\n[ 内存增长最多的部分 ]")
for stat in top_stats[:5]:
print(stat)
memory_profiler库memory_profiler提供更详细的内存使用分析:
# 安装: pip install memory_profiler
# 方法1: 装饰器方式
from memory_profiler import profile
@profile
def memory_heavy_function():
# 你的代码
big_list = [1] * 1000000
return sum(big_list)
memory_heavy_function()
# 方法2: 在代码中监控内存使用
from memory_profiler import memory_usage
import numpy as np
def create_large_array():
return np.random.rand(1000, 1000)
# 测量函数内存使用
mem_usage = memory_usage(create_large_array)
print(f"函数内存峰值: {max(mem_usage)} MB")
# 监控代码块内存使用
baseline = memory_usage()[0]
# 你的代码块
large_dict = {i: np.random.rand(100) for i in range(1000)}
current = memory_usage()[0]
print(f"代码块使用内存: {current - baseline} MB")
objgraph查看对象引用objgraph可以帮助找出内存泄漏和大对象:
# 安装: pip install objgraph
import objgraph
# 显示最常见的10种类型的对象数量
objgraph.show_most_common_types(limit=10)
# 查找特定类型的对象
large_lists = objgraph.by_type('list')[:5]
print(large_lists)
# 生成对象引用图(需要安装graphviz)
# pip install graphviz
some_object = [1, 2, [3, 4]]
objgraph.show_refs([some_object], filename='sample-graph.png')
创建一个实时内存监控脚本,可以在另一个进程中运行:
import psutil
import time
import os
import matplotlib.pyplot as plt
from datetime import datetime
def monitor_process(pid, interval=1, duration=60):
"""监控指定进程的内存使用情况"""
process = psutil.Process(pid)
# 收集数据
timestamps = []
memory_usage = []
start_time = time.time()
end_time = start_time + duration
print(f"开始监控进程 {pid} ({process.name()})")
print("时间\t\t内存使用(MB)")
while time.time() < end_time:
# 获取内存信息
mem_info = process.memory_info()
rss_mb = mem_info.rss / (1024 * 1024) # RSS内存(MB)
# 记录时间和内存使用
current_time = datetime.now().strftime('%H:%M:%S')
timestamps.append(time.time() - start_time)
memory_usage.append(rss_mb)
print(f"{current_time}\t{rss_mb:.2f} MB")
# 等待下一个间隔
time.sleep(interval)
# 绘制内存使用图
plt.figure(figsize=(10, 6))
plt.plot(timestamps, memory_usage)
plt.title(f"进程 {pid} ({process.name()}) 内存使用")
plt.xlabel("时间 (秒)")
plt.ylabel("内存使用 (MB)")
plt.grid(True)
plt.savefig(f"memory_usage_pid{pid}.png")
plt.show()
if __name__ == "__main__":
# 输入要监控的Python进程PID
target_pid = int(input("输入要监控的Python进程PID: "))
duration = int(input("监控持续时间(秒): "))
interval = float(input("采样间隔(秒): "))
monitor_process(target_pid, interval, duration)
windows 系统python程序运行时如何查看那个部分占用cpu最大
在Windows系统上查看Python程序中哪些部分占用CPU最多,可以使用以下几种方法:
cProfile模块Python标准库中的cProfile可以详细分析函数调用次数和执行时间:
import cProfile
import pstats
import io
# 方法1:直接分析整个程序
def main():
# 你的主程序代码
for i in range(1000000):
_ = i ** 2
# 执行分析
cProfile.run('main()', 'program_stats')
# 加载并显示结果
with open('program_stats', 'rb') as f:
stats = pstats.Stats(f)
stats.sort_stats('cumulative') # 按累计时间排序
stats.print_stats(20) # 显示前20个结果
# 方法2:分析特定函数
def cpu_intensive_function():
result = 0
for i in range(1000000):
result += i ** 2
return result
# 创建分析器对象
profiler = cProfile.Profile()
profiler.enable() # 开始分析
# 执行要分析的代码
cpu_intensive_function()
# 停止分析
profiler.disable()
# 输出结果到字符串
s = io.StringIO()
ps = pstats.Stats(profiler, stream=s).sort_stats('cumulative')
ps.print_stats(20)
print(s.getvalue())
line_profiler进行行级分析line_profiler可以精确到每行代码的执行时间:
# 安装: pip install line_profiler
# 在代码中添加装饰器
from line_profiler import LineProfiler
@profile # 不需要导入,line_profiler会注入这个装饰器
def cpu_heavy_function():
total = 0
for i in range(1000000):
total += i ** 2
for i in range(500000):
total -= i
return total
# 创建分析器
profiler = LineProfiler()
profiler.add_function(cpu_heavy_function) # 添加要分析的函数
# 执行分析
profiler.run('cpu_heavy_function()')
# 显示结果
profiler.print_stats()
使用命令行运行:
python -m line_profiler your_script.py.lprof
py-spy实时采样分析py-spy是一个低开销的采样分析器,可以在不修改代码的情况下分析运行中的Python程序:
# 安装
pip install py-spy
# 使用方法1:生成火焰图
py-spy record -o profile.svg --pid 12345 # 替换为你的Python进程PID
# 使用方法2:实时显示CPU占用
py-spy top --pid 12345
# 使用方法3:分析整个程序
py-spy record -o profile.svg -- python your_script.py
yappi进行多线程分析如果你的程序使用了多线程,yappi可以分析每个线程的CPU使用情况:
# 安装: pip install yappi
import yappi
import time
import threading
def cpu_intensive():
for i in range(10000000):
_ = i ** 2
def io_intensive():
for i in range(10):
time.sleep(0.1)
# 启动分析器
yappi.set_clock_type("cpu") # 使用CPU时间
yappi.start()
# 创建并启动线程
t1 = threading.Thread(target=cpu_intensive)
t2 = threading.Thread(target=io_intensive)
t1.start()
t2.start()
t1.join()
t2.join()
# 停止分析器
yappi.stop()
# 获取并打印线程统计信息
threads = yappi.get_thread_stats()
for thread in threads:
print(f"线程名: {thread.name}, CPU时间: {thread.ttot}")
# 获取并打印函数统计信息
print("\n函数统计:")
stats = yappi.get_func_stats()
stats.sort("ttot") # 按总时间排序
stats.print_all()
# 保存到文件
stats.save('callgrind.out', 'callgrind') # 可用KCachegrind查看
通过这些方法,Python 可以有效利用多核 CPU 资源,显著提升计算密集型应用的性能。
渐进式扩展:
优化内存使用:
监控系统资源:
对于大多数实际应用,6核16GB系统可以稳定运行10-30万协程,这已经能满足绝大多数高并发场景的需求。关键是根据应用特性找到最佳平衡点。
<!DOCTYPE html>
<html>
<head>
<title>WebSocket客户端</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
#messages {
height: 300px;
border: 1px solid #ccc;
overflow-y: scroll;
padding: 10px;
margin-bottom: 10px;
}
.message { margin-bottom: 5px; }
.server { color: blue; }
.client { color: green; }
.error { color: red; }
.status { color: gray; font-style: italic; }
</style>
</head>
<body>
<h2>WebSocket实时推送演示</h2>
<div id="connection-status" class="status">未连接</div>
<div id="messages"></div>
<input type="text" id="message-input" placeholder="发送消息...">
<button id="send-button">发送</button>
<button id="connect-button">连接</button>
<button id="disconnect-button">断开</button>
<script>
const messagesDiv = document.getElementById('messages');
const messageInput = document.getElementById('message-input');
const sendButton = document.getElementById('send-button');
const connectButton = document.getElementById('connect-button');
const disconnectButton = document.getElementById('disconnect-button');
const statusDiv = document.getElementById('connection-status');
let socket = null;
let reconnectAttempts = 0;
const maxReconnectAttempts = 5;
function connect() {
if (socket && socket.readyState === WebSocket.OPEN) return;
// 创建WebSocket连接
socket = new WebSocket('ws://localhost:8765');
socket.onopen = function(e) {
addMessage('连接已建立', 'status');
statusDiv.textContent = '已连接';
statusDiv.style.color = 'green';
reconnectAttempts = 0;
};
socket.onmessage = function(event) {
try {
const data = JSON.parse(event.data);
addMessage(`收到: ${JSON.stringify(data, null, 2)}`, 'server');
} catch (e) {
addMessage(`收到: ${event.data}`, 'server');
}
};
socket.onclose = function(event) {
if (event.wasClean) {
addMessage(`连接已关闭,代码=${event.code} 原因=${event.reason}`, 'status');
} else {
addMessage('连接中断', 'error');
}
statusDiv.textContent = '未连接';
statusDiv.style.color = 'red';
// 自动重连
if (reconnectAttempts < maxReconnectAttempts) {
reconnectAttempts++;
const delay = Math.min(1000 * reconnectAttempts, 5000);
addMessage(`${delay/1000}秒后尝试重连...`, 'status');
setTimeout(connect, delay);
}
};
socket.onerror = function(error) {
addMessage('WebSocket错误', 'error');
console.error('WebSocket错误:', error);
};
}
function disconnect() {
if (socket) {
socket.close(1000, "用户主动断开");
socket = null;
}
}
function sendMessage() {
if (!socket || socket.readyState !== WebSocket.OPEN) {
addMessage('未连接,无法发送消息', 'error');
return;
}
const message = messageInput.value.trim();
if (message) {
try {
// 尝试发送JSON
const jsonMsg = JSON.stringify({
type: "message",
content: message,
time: new Date().getTime()
});
socket.send(jsonMsg);
addMessage(`发送: ${message}`, 'client');
messageInput.value = '';
} catch (e) {
addMessage('发送失败: ' + e.message, 'error');
}
}
}
function addMessage(message, type) {
const messageElement = document.createElement('div');
messageElement.classList.add('message', type);
messageElement.textContent = message;
messagesDiv.appendChild(messageElement);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
// 事件监听
connectButton.addEventListener('click', connect);
disconnectButton.addEventListener('click', disconnect);
sendButton.addEventListener('click', sendMessage);
messageInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter')
import asyncio
import json
import time
import struct
import base64
import hashlib
import random
import os
import uuid
async def create_websocket_connection(host, port, path="/"):
"""创建WebSocket连接"""
# 建立TCP连接
reader, writer = await asyncio.open_connection(host, port)
# 生成WebSocket密钥
websocket_key = base64.b64encode(os.urandom(16)).decode()
# 构建HTTP升级请求
request = (
f"GET {path} HTTP/1.1\r\n"
f"Host: {host}:{port}\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
f"Sec-WebSocket-Key: {websocket_key}\r\n"
"Sec-WebSocket-Version: 13\r\n"
"\r\n"
)
# 发送请求
writer.write(request.encode())
await writer.drain()
# 读取响应头
response = b""
while True:
line = await reader.readline()
response += line
if line == b'\r\n' or not line:
break
# 检查响应是否成功
if b"HTTP/1.1 101" not in response:
writer.close()
await writer.wait_closed()
raise ConnectionError(f"WebSocket握手失败: {response.decode()}")
return reader, writer
async def encode_websocket_frame(data, opcode=0x01):
"""编码WebSocket帧"""
if isinstance(data, str):
data = data.encode('utf-8')
# 创建帧头部
header = bytes([0x80 | opcode]) # FIN + opcode
# 添加长度
length = len(data)
mask_bit = 0x80 # 客户端发送必须使用掩码
if length < 126:
header += bytes([mask_bit | length])
elif length < 65536:
header += bytes([mask_bit | 126]) + struct.pack("!H", length)
else:
header += bytes([mask_bit | 127]) + struct.pack("!Q", length)
# 生成掩码
mask = os.urandom(4)
header += mask
# 应用掩码到数据
masked_data = bytes(data[i] ^ mask[i % 4] for i in range(len(data)))
# 返回完整帧
return header + masked_data
async def decode_websocket_frame(reader):
"""解码WebSocket帧"""
# 读取帧头部
try:
header = await reader.readexactly(2)
except asyncio.IncompleteReadError:
return None, None # 连接关闭
# 解析基本头部
fin = (header[0] & 0x80) != 0
opcode = header[0] & 0x0F
has_mask = (header[1] & 0x80) != 0
payload_length = header[1] & 0x7F
# 获取扩展长度
if payload_length == 126:
length_bytes = await reader.readexactly(2)
payload_length = struct.unpack("!H", length_bytes)[0]
elif payload_length == 127:
length_bytes = await reader.readexactly(8)
payload_length = struct.unpack("!Q", length_bytes)[0]
# 获取掩码
if has_mask:
mask = await reader.readexactly(4)
else:
mask = None
# 读取有效载荷
if payload_length > 0:
payload = await reader.readexactly(payload_length)
else:
payload = b""
# 解码有效载荷
if has_mask and mask:
payload = bytes(payload[i] ^ mask[i % 4] for i in range(len(payload)))
return opcode, payload
async def websocket_client():
"""WebSocket客户端"""
try:
# 连接到WebSocket服务器
host = 'localhost'
port = 8765
print(f"连接到 WebSocket 服务器: {host}:{port}")
reader, writer = await create_websocket_connection(host, port)
print("WebSocket连接已建立")
# 创建接收任务
receive_task = asyncio.create_task(receive_messages(reader, writer))
import psutil
import os
import threading
import time
import gc
class MemoryMonitor:
def __init__(self, interval=5):
self.interval = interval
self.running = False
self.thread = None
self.peak_memory = 0
self.current_memory = 0
self.process = psutil.Process(os.getpid())
# 存储各模块内存使用
self.module_sizes = {}
def start(self):
"""开始内存监控"""
self.running = True
self.thread = threading.Thread(target=self._monitor_loop)
self.thread.daemon = True
self.thread.start()
def stop(self):
"""停止内存监控"""
self.running = False
if self.thread:
self.thread.join()
def _monitor_loop(self):
"""监控循环"""
while self.running:
# 获取当前内存使用
self.current_memory = self.process.memory_info().rss / (1024 * 1024)
# 更新峰值内存
if self.current_memory > self.peak_memory:
self.peak_memory = self.current_memory
# 当达到新峰值时分析对象
self._analyze_memory()
time.sleep(self.interval)
def _analyze_memory(self):
"""分析内存使用情况"""
print(f"\n[内存峰值] {self.peak_memory:.2f} MB")
# 强制垃圾回收
gc.collect()
# 获取所有对象
objects = gc.get_objects()
# 按类型统计内存
type_sizes = {}
for obj in objects:
obj_type = type(obj).__name__
try:
obj_size = sys.getsizeof(obj) / (1024 * 1024) # MB
if obj_type not in type_sizes:
type_sizes[obj_type] = 0
type_sizes[obj_type] += obj_size
except:
pass
# 显示最大的对象类型
print("最大内存占用的对象类型:")
for obj_type, size in sorted(type_sizes.items(), key=lambda x: x[1], reverse=True)[:10]:
print(f" {obj_type}: {size:.2f} MB")
# 分析大型容器
large_lists = [obj for obj in objects if isinstance(obj, list) and len(obj) > 1000]
large_dicts = [obj for obj in objects if isinstance(obj, dict) and len(obj) > 1000]
print(f"大型列表数量: {len(large_lists)}")
print(f"大型字典数量: {len(large_dicts)}")
# 使用示例
if __name__ == "__main__":
import sys
# 创建并启动内存监控器
monitor = MemoryMonitor(interval=2)
monitor.start()
try:
# 你的主程序代码
print("程序开始运行,内存监控已启动")
# 示例:创建一些大对象
big_list = []
for i in range(10):
print(f"创建数据块 {i}")
big_list.append([0] * 1000000) # 每次添加约8MB数据
time.sleep(1)
print("清理数据...")
big_list = None
gc.collect()
time.sleep(5)
finally:
# 停止监控并显示结果
monitor.stop()
print(f"\n程序结束,峰值内存使用: {monitor.peak_memory:.2f} MB")
任务管理器:
Ctrl+Shift+Esc 打开任务管理器Process Explorer (更强大的工具):
如果你使用PyCharm专业版:
找出大型变量:
import sys
# 获取当前模块的所有变量
variables = globals().copy()
# 按大小排序并显示
for var_name, var_value in sorted(
((name, value) for name, value in variables.items()
if not name.startswith('_')),
key=lambda item: sys.getsizeof(item[1]),
reverse=True)[:10]:
print(f"{var_name}: {sys.getsizeof(var_value)/1024/1024:.2f} MB")
检测内存泄漏:
import gc
import weakref
class LeakDetector:
def __init__(self, obj):
self.obj_ref = weakref.ref(obj)
self.obj_id = id(obj)
def check(self):
return self.obj_ref() is not None
# 使用示例
test_obj = [1, 2, 3]
detector = LeakDetector(test_obj)
# 删除对象引用
del test_obj
gc.collect()
# 检查对象是否仍存在
if detector.check():
print(f"可能存在内存泄漏: 对象 {detector.obj_id} 仍在内存中")
else:
print("对象已被正确清理")
通过这些工具和方法,你可以全面了解Python程序在Windows系统上的内存使用情况,找出占用内存最大的部分,并优化你的代码。
以下是一个实时监控Python进程CPU使用的脚本:
import psutil
import time
import os
import matplotlib.pyplot as plt
from datetime import datetime
def monitor_cpu_usage(pid, interval=1, duration=60):
"""监控指定进程的CPU使用情况"""
process = psutil.Process(pid)
# 收集数据
timestamps = []
cpu_percentages = []
start_time = time.time()
end_time = start_time + duration
print(f"开始监控进程 {pid} ({process.name()})")
print("时间\t\tCPU使用率(%)")
while time.time() < end_time:
# 获取CPU使用率
cpu_percent = process.cpu_percent(interval=0.1)
# 记录时间和CPU使用率
current_time = datetime.now().strftime('%H:%M:%S')
timestamps.append(time.time() - start_time)
cpu_percentages.append(cpu_percent)
print(f"{current_time}\t{cpu_percent:.2f}%")
# 等待下一个间隔
time.sleep(interval)
# 绘制CPU使用图
plt.figure(figsize=(10, 6))
plt.plot(timestamps, cpu_percentages)
plt.title(f"进程 {pid} ({process.name()}) CPU使用率")
plt.xlabel("时间 (秒)")
plt.ylabel("CPU使用率 (%)")
plt.grid(True)
plt.savefig(f"cpu_usage_pid{pid}.png")
plt.show()
if __name__ == "__main__":
# 输入要监控的Python进程PID
target_pid = int(input("输入要监控的Python进程PID: "))
duration = int(input("监控持续时间(秒): "))
interval = float(input("采样间隔(秒): "))
monitor_cpu_usage(target_pid, interval, duration)
scalene进行CPU和内存分析scalene是一个高精度的Python分析器,可以同时分析CPU和内存使用:
# 安装: pip install scalene
# 使用方法
# 1. 命令行运行
# scalene your_script.py
# 2. 在代码中使用
import scalene
# 开始分析
scalene.start()
# 你的代码
def cpu_intensive():
result = 0
for i in range(10000000):
result += i
return result
cpu_intensive()
# 停止分析并生成报告
scalene.stop()
import cProfile
import pstats
import io
import time
import threading
import os
class CPUProfiler:
def __init__(self, interval=60):
"""
初始化CPU分析器
interval: 分析间隔(秒)
"""
self.interval = interval
self.profiler = None
self.running = False
self.thread = None
self.profile_count = 0
self.output_dir = "cpu_profiles"
# 创建输出目录
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
def start(self):
"""开始周期性CPU分析"""
self.running = True
self.thread = threading.Thread(target=self._profile_loop)
self.thread.daemon = True
self.thread.start()
def stop(self):
"""停止CPU分析"""
self.running = False
if self.thread:
self.thread.join()
def _profile_loop(self):
"""周期性分析循环"""
while self.running:
# 开始一次分析
self._start_profile()
# 等待指定时间
time.sleep(self.interval)
# 结束分析并保存结果
self._stop_and_save_profile()
def _start_profile(self):
"""开始一次分析"""
self.profiler = cProfile.Profile()
self.profiler.enable()
print(f"CPU分析开始 #{self.profile_count}")
def _stop_and_save_profile(self):
"""结束分析并保存结果"""
if self.profiler:
self.profiler.disable()
# 生成时间戳
timestamp = time.strftime("%Y%m%d-%H%M%S")
# 保存原始分析数据
profile_file = f"{self.output_dir}/profile_{timestamp}_{self.profile_count}.prof"
self.profiler.dump_stats(profile_file)
# 生成可读报告
report_file = f"{self.output_dir}/report_{timestamp}_{self.profile_count}.txt"
with open(report_file, 'w') as f:
stats = pstats.Stats(self.profiler, stream=f)
stats.sort_stats('cumulative')
stats.print_stats(30) # 前30个结果
print(f"CPU分析 #{self.profile_count} 完成,结果保存到 {report_file}")
self.profile_count += 1
self.profiler = None
# 使用示例
if __name__ == "__main__":
# 创建并启动CPU分析器
profiler = CPUProfiler(interval=10) # 每10秒分析一次
profiler.start()
try:
# 你的主程序代码
print("程序开始运行,CPU分析已启动")
# 模拟不同的CPU密集型任务
for i in range(5):
print(f"执行任务 {i}")
# 任务1: 数学计算
if i % 2 == 0:
result = 0
for j in range(10000000):
result += j ** 2
# 任务2: 列表操作
else:
data = []
for j in range(1000000):
data.append(j)
if len(data) > 10000:
data = data[-10000:]
time.sleep(5)
finally:
# 停止分析器
profiler.stop()
print("程序结束,CPU分析已停止")
任务管理器:
Ctrl+Shift+Esc 打开任务管理器Process Explorer (更详细的工具):
如果你使用VS Code:
定位热点函数:
import time
def time_function(func, *args, **kwargs):
"""测量函数执行时间"""
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} 执行时间: {end - start:.6f} 秒")
return result
# 使用示例
def slow_function(n):
total = 0
for i in range(n):
total += i ** 2
return total
time_function(slow_function, 1000000)
分析代码块:
import time
import contextlib
@contextlib.contextmanager
def timer(name):
"""计时上下文管理器"""
start = time.time()
yield
end = time.time()
print(f"{name} 执行时间: {end - start:.6f} 秒")
# 使用示例
with timer("循环操作"):
total = 0
for i in range(1000000):
total += i
使用装饰器自动分析函数:
import functools
import time
def profile(func):
"""分析函数执行时间的装饰器"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} 执行时间: {end - start:.6f} 秒")
return result
return wrapper
# 使用示例
@profile
def slow_calculation(n):
return sum(i**2 for i in range(n))
slow_calculation(1000000)
通过这些工具和方法,你可以全面了解Python程序在Windows系统上的CPU使用情况,找出占用CPU最多的代码部分,并进行有针对性的优化。