帮我编写一个测试CPU和GPU推理对比的python脚本
时间: 2024-10-23 07:05:48 浏览: 18
在Python中,我们可以使用一些库如`tensorflow`, `pytorch`, 或者`cupy`来进行CPU和GPU性能的比较。这里是一个基本的示例,我们将使用TensorFlow来展示如何在CPU和GPU上运行简单的矩阵乘法:
```python
import tensorflow as tf
import time
# 创建一个简单的矩阵
matrix = tf.random.uniform((5000, 5000), dtype=tf.float32)
def run_on_cpu():
with tf.device('/cpu:0'):
start_time = time.time()
cpu_result = tf.matmul(matrix, matrix)
print(f"CPU Time: {time.time() - start_time} seconds")
def run_on_gpu():
if tf.config.list_physical_devices('GPU'):
with tf.device('/gpu:0'):
start_time = time.time()
gpu_result = tf.matmul(matrix, matrix)
print(f"GPU Time: {time.time() - start_time} seconds")
# 如果有GPU,对比两者的速度
print("Speedup (GPU/CPU):", (start_time - run_on_cpu().timestamp) / (time.time() - start_time))
run_on_cpu()
run_on_gpu()
#
阅读全文