python:多线程性能测量

技术:

  1. 多线程、多线程共享变量
  2. 测量:总的显存占用大小、某个进程的内存占用大小、某个进程的CPU占用率
import os
import time
import psutil
import pynvml
from multiprocessing import Process, Manager

# MiB
def gpu_statistic(gpus_per):
	pynvml.nvmlInit()
	handle = pynvml.nvmlDeviceGetHandleByIndex(0)
	while (True):
		used_gpu_mem = pynvml.nvmlDeviceGetMemoryInfo(handle).used
		gpus_per.append(used_gpu_mem * 1.0 / 1024 / 1024)
		time.sleep(0.5)
 
# MiB
def mem_statistic(mems_per, pid):
	p = psutil.Process(pid)
	while (True):
		mems_per.append(p.memory_info().rss * 1.0 / 1024 / 1024)
		time.sleep(0.5)
 
# %
def cpu_statistic(cpus_per, pid):
	p = psutil.Process(pid)
	while (True):
		cpus_per.append(p.cpu_times().user)
		time.sleep(0.5)
 
if __name__ == '__main__':
	gpus_all = []
	mems_all = []
	cpus_all = []
 
        manager = Manager()
 
	x = 1
	while(x < 5):
		x += 1
 
        	gpus_per = manager.list()
        	mems_per = manager.list()
        	cpus_per = manager.list()
 
		pid = os.getpid()
        	gpu_process = Process(target = gpu_statistic, args = (gpus_per,))
        	mem_process = Process(target = mem_statistic, args = (mems_per, pid))
        	cpu_process = Process(target = cpu_statistic, args = (cpus_per, pid))
 
        	gpu_process.start()
        	mem_process.start()
        	cpu_process.start()
 
		time.sleep(2)
 
		gpus_all.append(gpus_per[:])
		mems_all.append(mems_per[:])
		cpus_all.append(cpus_per[:])
 
        	gpu_process.terminate()
        	mem_process.terminate()
        	cpu_process.terminate()
 
	print gpus_all
	print mems_all
	print cpus_all

 

### 评估Python多线程程序性能的方法 #### 使用 `time` 模块测量执行时间 最简单的方式是利用内置模块 `time` 来记录函数前后的时间差,以此来衡量一段代码的运行效率。 ```python import time import threading def task(): start_time = time.time() # 假设这里有一些耗时操作 time.sleep(2) end_time = time.time() print(f"Task took {end_time - start_time} seconds") if __name__ == "__main__": threads = [] for _ in range(5): # 创建多个线程 t = threading.Thread(target=task) threads.append(t) t.start() for t in threads: t.join() # 等待所有子线程完成 total_end_time = time.time() print(f"All tasks completed, total elapsed time is {total_end_time - start_time} seconds") ``` 这种方法虽然直观易懂,但对于更复杂的场景可能不够精确[^1]。 #### 利用 `cProfile` 进行详尽分析 对于想要深入了解各个部分具体消耗了多少资源的情况,则可以采用标准库中的 `cProfile` 工具来进行更加细致入微的功能剖析。它能够统计出每一个被调用过的函数及其对应的次数、总时间和平均时间等信息。 ```python import cProfile from concurrent.futures import ThreadPoolExecutor def heavy_computation(n): sum = 0 for i in range(n * n): sum += (i % 7) ** 2 return sum with ThreadPoolExecutor(max_workers=4) as executor: futures = [executor.submit(heavy_computation, x) for x in range(1_000)] list(map(lambda f: f.result(), futures)) profiler = cProfile.Profile() profiler.enable() # 上述多线程逻辑再次执行... profiler.disable() profiler.print_stats(sort='cumulative') ``` 此方式有助于识别瓶颈所在之处,并据此优化算法设计或调整参数配置. #### 应用第三方库如 `line_profiler` 当关注点聚焦于某几行特定的关键路径上时,还可以借助外部扩展包比如 `line_profiler` 实现逐行级别的性能监测。安装之后只需加上装饰器即可开启跟踪模式: ```bash pip install line-profiler ``` ```python @profile def critical_section(data_chunk): result = [] for item in data_chunk: processed_item = complex_operation(item) # 耗时的操作 result.append(processed_item) return result chunks = divide_data_into_chunks(large_dataset) threads = [] for chunk in chunks: thd = threading.Thread(target=critical_section, args=(chunk,)) threads.append(thd) thd.start() for thd in threads: thd.join() ``` 上述三种手段各有侧重,在不同需求背景下发挥着不可替代的作用。选择合适的技术方案取决于具体的开发环境和个人偏好[^2].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值