前提

1.安装好tensorflow的gpu版本及其对应CUDA

2.有GPU

1.指定某一块或多块gpu运行

方法一

1
2
# 指定第二块gpu
CUDA_VISIBLE_DEVICES=1 python {xxx}.py

方法二

1
2
export CUDA_VISIBLE_DEVICES=1
python {xxx}.py

方法三

1
2
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "2"

参数参考:

Environment Variable Syntax Results
CUDA_VISIBLE_DEVICES=1 Only device 1 will be seen
CUDA_VISIBLE_DEVICES=0,1 Devices 0 and 1 will be visible
CUDA_VISIBLE_DEVICES=“0,1” Same as above, quotation marks are optional
CUDA_VISIBLE_DEVICES=0,2,3 Devices 0, 2, 3 will be visible; device 1 is masked
CUDA_VISIBLE_DEVICES="" No GPU will be visible

2.配置gpu显存使用率

方法一:通过配置Session的运行参数配置gpu的使用

1
2
3
4
5
# 通过配置Session的运行参数配置gpu的使用

config = tf.ConfigProto(allow_soft_placement=True, allow_soft_placement=True)
config.gpu_options.per_process_gpu_memory_fraction = 0.4 #占用40%显存
sess = tf.Session(config=config)

参数参考:

Syntax Results
tf.ConfigProto(log_device_placement=True) 记录设备指派情况
tf.ConfigProto(allow_soft_placement=True) 自动选择一个运行备
config.gpu_options.allow_growth = True 动态申请显存
config.gpu_options.per_process_gpu_memory_fraction = 0.4 限制GPU使用率