MCPcopy Create free account
hub / github.com/NVIDIA/cuda-samples / get_gpu_count

Function get_gpu_count

run_tests.py:134–171  ·  view source on GitHub ↗

Return the number of NVIDIA GPUs visible on the system. The function first tries to use the `nvidia-smi` CLI which should be available on most systems with a CUDA-capable driver installed. If the command is not present or fails we fall back to checking the CUDA_VISIBLE_DEVICES envi

()

Source from the content-addressed store, hash-verified

132 return {"name": exe_name, "description": run_description, "return_code": -1, "status": f"Error: {str(e)}"}
133
134def get_gpu_count():
135 """Return the number of NVIDIA GPUs visible on the system.
136
137 The function first tries to use the `nvidia-smi` CLI which should be
138 available on most systems with a CUDA-capable driver installed. If the
139 command is not present or fails we fall back to checking the
140 CUDA_VISIBLE_DEVICES environment variable. The fallback is conservative
141 – if we cannot determine the GPU count we assume 0."""
142
143 # Try the recommended NVML/nvidia-smi approach first
144 try:
145 smi = subprocess.run(
146 ["nvidia-smi", "-L"],
147 stdout=subprocess.PIPE,
148 stderr=subprocess.DEVNULL,
149 text=True,
150 check=False,
151 )
152 if smi.returncode == 0:
153 # Each GPU is reported on its own line that starts with "GPU 0:" etc.
154 gpu_lines = [ln for ln in smi.stdout.strip().splitlines() if ln.strip().lower().startswith("gpu ")]
155 if gpu_lines:
156 return len(gpu_lines)
157 except FileNotFoundError:
158 # nvidia-smi is missing – may be WSL/no driver inside container etc.
159 pass
160 except Exception:
161 # Any unexpected error – treat as unknown → 0
162 pass
163
164 # Fallback: attempt to infer from CUDA_VISIBLE_DEVICES if it is set and not empty
165 visible = os.environ.get("CUDA_VISIBLE_DEVICES", "").strip()
166 if visible and visible not in {"no", "none"}:
167 # Handles comma-separated list like "0,1,2" or single values
168 return len([v for v in visible.split(',') if v])
169
170 # Unable to determine, assume no GPUs
171 return 0
172
173def main():
174 parser = argparse.ArgumentParser(description='Run all executables and capture output')

Callers 1

mainFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected