//--------------------------------------------------------------------------
// Project: 
// Select the least utilized GPU on a CUDA-enabled system.
// Insert into your code as desired. 
//
// Prerequisites: 
// Must have installed the CUDA toolkit.
// Must be running on a UNIX machine
//
// Independent testing info:
// Compile on commandline: nvcc least_utilized_GPU.cu -o test
// run on commandline: ./test
//
// Author: Jordan Bonilla
// Date  : April 2016
// License: All rights Reserved. See LICENSE.txt
//--------------------------------------------------------------------------

#include <cstdio> // printf
#include <stdlib.h> // popen, pclose, atoi, fread
#include <cuda_runtime.h> // cudaGetDeviceCount, cudaSetDevice

// Select the least utilized GPU on this system. Estimate
// GPU utilization using GPU temperature. UNIX only.
void select_GPU() 
{
  // Get the number of GPUs on this machine
  int num_devices;
  cudaGetDeviceCount(&num_devices);
  if(num_devices == 1) {
    return;
  }
  // Read GPU info into buffer "output"
  const unsigned int MAX_BYTES = 10000;
  char output[MAX_BYTES];
  FILE *fp = popen("nvidia-smi &> /dev/null", "r");
  fread(output, sizeof(char), MAX_BYTES, fp);
  pclose(fp);
  // array to hold GPU temperatures
  int * temperatures = new int[num_devices];
  // parse output for temperatures using knowledge of "nvidia-smi" output format
  int i = 0;
  unsigned int num_temps_parsed = 0;
  while(output[i] != '\0') {
    if(output[i] == '%') {
      unsigned int temp_begin = i + 1;
      while(output[i] != 'C') {
        ++i;
      }
      unsigned int temp_end = i;
      char this_temperature[32];
      // Read in the characters cooresponding to this temperature
      for(int j = 0; j < temp_end - temp_begin; ++j) {
          this_temperature[j] = output[temp_begin + j];
      }
      this_temperature[temp_end - temp_begin + 1] = '\0';
      // Convert the string representation to an int
      temperatures[num_temps_parsed] = atoi(this_temperature);
      num_temps_parsed++;
    }
    ++i;
  }
  // Get GPU with lowest temperature
  int min_temp = 1e7, index_of_min = -1;
  for (int i = 0; i < num_devices; i++) 
  {
    int candidate_min = temperatures[i];
    if(candidate_min < min_temp) 
    {
      min_temp = candidate_min;
      index_of_min = i;
    }
  }
  // Tell CUDA to use the GPU with the lowest temeprature
  printf("Index of the GPU with the lowest temperature: %d (%d C)\n", 
    index_of_min, min_temp);
  cudaSetDevice(index_of_min);
  // Free memory and return
  delete(temperatures);
  return;
}

int main(int argc, char **argv) {
  select_GPU();
  return 0;
}



	.file	"tmpxft_00228b98_00000000-6_least_utilized_GPU.cudafe1.cpp"
	.text
#APP

#NO_APP
	.type	_ZL26__cudaUnregisterBinaryUtilv, @function
_ZL26__cudaUnregisterBinaryUtilv:
.LFB2031:
	.cfi_startproc
	endbr64
	movq	_ZL20__cudaFatCubinHandle(%rip), %rdi
	jmp	__cudaUnregisterFatBinary@PLT
	.cfi_endproc
.LFE2031:
	.size	_ZL26__cudaUnregisterBinaryUtilv, .-_ZL26__cudaUnregisterBinaryUtilv
	.section	.rodata.str1.1,"aMS",@progbits,1
.LC0:
	.string	"r"
.LC1:
	.string	"nvidia-smi &> /dev/null"
.LC2:
	.string	"Index of the GPU with the lowest temperature: %d (%d C)\n"
	.text
	.globl	_Z10select_GPUv
	.type	_Z10select_GPUv, @function
_Z10select_GPUv:
.LFB2027:
	.cfi_startproc
	endbr64
	pushq	%r14
	.cfi_def_cfa_offset 16
	.cfi_offset 14, -16
	pushq	%r13
	.cfi_def_cfa_offset 24
	.cfi_offset 13, -24
	pushq	%r12
	.cfi_def_cfa_offset 32
	.cfi_offset 12, -32
	pushq	%rbp
	.cfi_def_cfa_offset 40
	.cfi_offset 6, -40
	pushq	%rbx
	.cfi_def_cfa_offset 48
	.cfi_offset 3, -48
	subq	$4096, %rsp
	.cfi_def_cfa_offset 4144
	orq	$0, (%rsp)
	subq	$4096, %rsp
	.cfi_def_cfa_offset 8240
	orq	$0, (%rsp)
	subq	$1856, %rsp
	.cfi_def_cfa_offset 10096
	movq	%fs:40, %rax
	movq	%rax, 10040(%rsp)
	xorl	%eax, %eax
	leaq	4(%rsp), %rdi
	call	cudaGetDeviceCount@PLT
	cmpl	$1, 4(%rsp)
	je	.L2
	leaq	.LC0(%rip), %rsi
	leaq	.LC1(%rip), %rdi
	call	popen@PLT
	leaq	40(%rsp), %rbp
	movl	$10000, %ecx
	movl	$1, %edx
	movq	%rax, %rbx
	movq	%rax, %r8
	movl	$10000, %esi
	movq	%rbp, %rdi
	call	__fread_chk@PLT
	movq	%rbx, %rdi
	call	pclose@PLT
	movslq	4(%rsp), %rdi
	movabsq	$2305843009213693950, %rax
	cmpq	%rdi, %rax
	jb	.L4
	salq	$2, %rdi
	xorl	%r12d, %r12d
	call	_Znam@PLT
	xorl	%ecx, %ecx
	movq	%rax, %rbx
	jmp	.L5
.L4:
	movq	10040(%rsp), %rax
	subq	%fs:40, %rax
	jne	.L18
	call	__cxa_throw_bad_array_new_length@PLT
.L21:
	subl	%ecx, %eax
	movb	$0, 8(%rsp,%rax)
	movl	%r12d, %eax
	incl	%r12d
	leaq	(%rbx,%rax,4), %r14
	call	atoi@PLT
	movl	%r13d, %ecx
	movl	%eax, (%r14)
.L7:
	incl	%ecx
.L5:
	movslq	%ecx, %rdx
	movb	40(%rsp,%rdx), %al
	testb	%al, %al
	je	.L20
	cmpb	$37, %al
	jne	.L7
	leal	1(%rcx), %eax
.L8:
	movb	0(%rbp,%rdx), %sil
	movq	%rdx, %r13
	leaq	1(%rdx), %rdx
	cmpb	$67, %sil
	jne	.L8
	leaq	8(%rsp), %rdx
	movl	%r13d, %esi
	movq	%rdx, %rdi
.L9:
	cmpl	%esi, %eax
	je	.L21
	movl	%eax, %r8d
	incq	%rdx
	incl	%eax
	movb	40(%rsp,%r8), %r8b
	movb	%r8b, -1(%rdx)
	jmp	.L9
.L20:
	movl	4(%rsp), %esi
	xorl	%eax, %eax
	orl	$-1, %ebp
	movl	$10000000, %ecx
.L12:
	cmpl	%eax, %esi
	jle	.L22
	movl	(%rbx,%rax,4), %edx
	cmpl	%edx, %ecx
	jle	.L13
	movl	%eax, %ebp
	movl	%edx, %ecx
.L13:
	incq	%rax
	jmp	.L12
.L22:
	leaq	.LC2(%rip), %rsi
	movl	%ebp, %edx
	movl	$2, %edi
	xorl	%eax, %eax
	call	__printf_chk@PLT
	movl	%ebp, %edi
	call	cudaSetDevice@PLT
	movl	$4, %esi
	movq	%rbx, %rdi
	call	_ZdlPvm@PLT
.L2:
	movq	10040(%rsp), %rax
	subq	%fs:40, %rax
	je	.L15
.L18:
	call	__stack_chk_fail@PLT
.L15:
	addq	$10048, %rsp
	.cfi_def_cfa_offset 48
	popq	%rbx
	.cfi_def_cfa_offset 40
	popq	%rbp
	.cfi_def_cfa_offset 32
	popq	%r12
	.cfi_def_cfa_offset 24
	popq	%r13
	.cfi_def_cfa_offset 16
	popq	%r14
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE2027:
	.size	_Z10select_GPUv, .-_Z10select_GPUv
	.section	.text.startup,"ax",@progbits
	.globl	main
	.type	main, @function
main:
.LFB2028:
	.cfi_startproc
	endbr64
	pushq	%rax
	.cfi_def_cfa_offset 16
	call	_Z10select_GPUv
	xorl	%eax, %eax
	popq	%rdx
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE2028:
	.size	main, .-main
	.type	_ZL24__sti____cudaRegisterAllv, @function
_ZL24__sti____cudaRegisterAllv:
.LFB2054:
	.cfi_startproc
	endbr64
	pushq	%rax
	.cfi_def_cfa_offset 16
	leaq	_ZL15__fatDeviceText(%rip), %rdi
	call	__cudaRegisterFatBinary@PLT
	movq	%rax, %rdi
	movq	%rax, _ZL20__cudaFatCubinHandle(%rip)
	call	__cudaRegisterFatBinaryEnd@PLT
	leaq	_ZL26__cudaUnregisterBinaryUtilv(%rip), %rdi
	popq	%rdx
	.cfi_def_cfa_offset 8
	jmp	atexit@PLT
	.cfi_endproc
.LFE2054:
	.size	_ZL24__sti____cudaRegisterAllv, .-_ZL24__sti____cudaRegisterAllv
	.section	.init_array,"aw"
	.align 8
	.quad	_ZL24__sti____cudaRegisterAllv
	.section	.nvFatBinSegment,"aw"
	.align 8
	.type	_ZL15__fatDeviceText, @object
	.size	_ZL15__fatDeviceText, 24
_ZL15__fatDeviceText:
	.long	1180844977
	.long	1
	.quad	fatbinData
	.quad	0
	.local	_ZL20__cudaFatCubinHandle
	.comm	_ZL20__cudaFatCubinHandle,8,8
	.ident	"GCC: (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0"
	.section	.note.GNU-stack,"",@progbits
	.section	.note.gnu.property,"a"
	.align 8
	.long	1f - 0f
	.long	4f - 1f
	.long	5
0:
	.string	"GNU"
1:
	.align 8
	.long	0xc0000002
	.long	3f - 2f
2:
	.long	0x3
3:
	.align 8
4:

//--------------------------------------------------------------------------
// Project: 
// Select the least utilized GPU on a CUDA-enabled system.
// Insert into your code as desired. 
//
// Prerequisites: 
// Must have installed the CUDA toolkit.
// Must be running on a UNIX machine
//
// Independent testing info:
// Compile on commandline: nvcc least_utilized_GPU.cu -o test
// run on commandline: ./test
//
// Author: Jordan Bonilla
// Date  : April 2016
// License: All rights Reserved. See LICENSE.txt
//--------------------------------------------------------------------------

#include <cstdio> // printf
#include <stdlib.h> // popen, pclose, atoi, fread
#include <hip/hip_runtime.h> // cudaGetDeviceCount, cudaSetDevice

// Select the least utilized GPU on this system. Estimate
// GPU utilization using GPU temperature. UNIX only.
void select_GPU() 
{
  // Get the number of GPUs on this machine
  int num_devices;
  hipGetDeviceCount(&num_devices);
  if(num_devices == 1) {
    return;
  }
  // Read GPU info into buffer "output"
  const unsigned int MAX_BYTES = 10000;
  char output[MAX_BYTES];
  FILE *fp = popen("nvidia-smi &> /dev/null", "r");
  fread(output, sizeof(char), MAX_BYTES, fp);
  pclose(fp);
  // array to hold GPU temperatures
  int * temperatures = new int[num_devices];
  // parse output for temperatures using knowledge of "nvidia-smi" output format
  int i = 0;
  unsigned int num_temps_parsed = 0;
  while(output[i] != '\0') {
    if(output[i] == '%') {
      unsigned int temp_begin = i + 1;
      while(output[i] != 'C') {
        ++i;
      }
      unsigned int temp_end = i;
      char this_temperature[32];
      // Read in the characters cooresponding to this temperature
      for(int j = 0; j < temp_end - temp_begin; ++j) {
          this_temperature[j] = output[temp_begin + j];
      }
      this_temperature[temp_end - temp_begin + 1] = '\0';
      // Convert the string representation to an int
      temperatures[num_temps_parsed] = atoi(this_temperature);
      num_temps_parsed++;
    }
    ++i;
  }
  // Get GPU with lowest temperature
  int min_temp = 1e7, index_of_min = -1;
  for (int i = 0; i < num_devices; i++) 
  {
    int candidate_min = temperatures[i];
    if(candidate_min < min_temp) 
    {
      min_temp = candidate_min;
      index_of_min = i;
    }
  }
  // Tell CUDA to use the GPU with the lowest temeprature
  printf("Index of the GPU with the lowest temperature: %d (%d C)\n", 
    index_of_min, min_temp);
  hipSetDevice(index_of_min);
  // Free memory and return
  delete(temperatures);
  return;
}

int main(int argc, char **argv) {
  select_GPU();
  return 0;
}



	.text
	.file	"least_utilized_GPU.hip"
	.globl	_Z10select_GPUv                 # -- Begin function _Z10select_GPUv
	.type	_Z10select_GPUv,@function
_Z10select_GPUv:                        # @_Z10select_GPUv
	.cfi_startproc
# %bb.0:
	pushq	%rbp
	.cfi_def_cfa_offset 16
	pushq	%r15
	.cfi_def_cfa_offset 24
	pushq	%r14
	.cfi_def_cfa_offset 32
	pushq	%r13
	.cfi_def_cfa_offset 40
	pushq	%r12
	.cfi_def_cfa_offset 48
	pushq	%rbx
	.cfi_def_cfa_offset 56
	subq	$10056, %rsp                    # imm = 0x2748
	.cfi_def_cfa_offset 10112
	.cfi_offset %rbx, -56
	.cfi_offset %r12, -48
	.cfi_offset %r13, -40
	.cfi_offset %r14, -32
	.cfi_offset %r15, -24
	.cfi_offset %rbp, -16
	leaq	12(%rsp), %rbx
	movq	%rbx, %rdi
	callq	hipGetDeviceCount
	cmpl	$1, (%rbx)
	je	.LBB0_16
# %bb.1:
	movl	$.L.str, %edi
	movl	$.L.str.1, %esi
	callq	popen
	movq	%rax, %rbx
	leaq	48(%rsp), %rdi
	movl	$1, %esi
	movl	$10000, %edx                    # imm = 0x2710
	movq	%rax, %rcx
	callq	fread
	movq	%rbx, %rdi
	callq	pclose
	movslq	12(%rsp), %rax
	leaq	(,%rax,4), %rcx
	testq	%rax, %rax
	movl	%eax, %r15d
	movq	$-1, %rdi
	cmovnsq	%rcx, %rdi
	callq	_Znam
	movq	%rax, %rbx
	xorl	%r12d, %r12d
	leaq	16(%rsp), %r14
	xorl	%r13d, %r13d
.LBB0_2:                                # =>This Loop Header: Depth=1
                                        #     Child Loop BB0_7 Depth 2
                                        #     Child Loop BB0_10 Depth 2
	movslq	%r13d, %rax
	movzbl	48(%rsp,%rax), %ecx
	cmpl	$37, %ecx
	je	.LBB0_6
# %bb.3:                                #   in Loop: Header=BB0_2 Depth=1
	testl	%ecx, %ecx
	jne	.LBB0_12
	jmp	.LBB0_4
.LBB0_6:                                # %.preheader59.preheader
                                        #   in Loop: Header=BB0_2 Depth=1
	leaq	(%rsp,%rax), %rcx
	addq	$48, %rcx
	xorl	%eax, %eax
.LBB0_7:                                # %.preheader59
                                        #   Parent Loop BB0_2 Depth=1
                                        # =>  This Inner Loop Header: Depth=2
	decl	%eax
	cmpb	$67, (%rcx)
	leaq	1(%rcx), %rcx
	jne	.LBB0_7
# %bb.8:                                #   in Loop: Header=BB0_2 Depth=1
	movl	%eax, %ecx
	subl	$-2, %ecx
	je	.LBB0_11
# %bb.9:                                # %.lr.ph.preheader
                                        #   in Loop: Header=BB0_2 Depth=1
	leal	1(%r13), %edx
	negl	%ecx
	movl	%ecx, %ecx
	movl	%edx, %edx
	xorl	%esi, %esi
.LBB0_10:                               # %.lr.ph
                                        #   Parent Loop BB0_2 Depth=1
                                        # =>  This Inner Loop Header: Depth=2
	leal	(%rdx,%rsi), %edi
	movb	48(%rsp,%rdi), %dil
	movb	%dil, 16(%rsp,%rsi)
	incq	%rsi
	cmpq	%rcx, %rsi
	jb	.LBB0_10
.LBB0_11:                               # %._crit_edge
                                        #   in Loop: Header=BB0_2 Depth=1
	notl	%eax
	addl	%eax, %r13d
	movb	$0, 16(%rsp,%rax)
	movq	%r14, %rdi
	callq	atoi
	movl	%r12d, %ecx
	movl	%eax, (%rbx,%rcx,4)
	incl	%r12d
.LBB0_12:                               #   in Loop: Header=BB0_2 Depth=1
	incl	%r13d
	jmp	.LBB0_2
.LBB0_4:                                # %.preheader
	testl	%r15d, %r15d
	jle	.LBB0_5
# %bb.13:                               # %.lr.ph49.preheader
	movl	$10000000, %edx                 # imm = 0x989680
	movl	$-1, %ebp
	xorl	%eax, %eax
.LBB0_14:                               # %.lr.ph49
                                        # =>This Inner Loop Header: Depth=1
	movl	(%rbx,%rax,4), %ecx
	cmpl	%edx, %ecx
	cmovll	%ecx, %edx
	cmovll	%eax, %ebp
	incq	%rax
	cmpq	%rax, %r15
	jne	.LBB0_14
	jmp	.LBB0_15
.LBB0_5:
	movl	$-1, %ebp
	movl	$10000000, %edx                 # imm = 0x989680
.LBB0_15:                               # %._crit_edge50
	movl	$.L.str.2, %edi
	movl	%ebp, %esi
	xorl	%eax, %eax
	callq	printf
	movl	%ebp, %edi
	callq	hipSetDevice
	movq	%rbx, %rdi
	callq	_ZdlPv
.LBB0_16:
	addq	$10056, %rsp                    # imm = 0x2748
	.cfi_def_cfa_offset 56
	popq	%rbx
	.cfi_def_cfa_offset 48
	popq	%r12
	.cfi_def_cfa_offset 40
	popq	%r13
	.cfi_def_cfa_offset 32
	popq	%r14
	.cfi_def_cfa_offset 24
	popq	%r15
	.cfi_def_cfa_offset 16
	popq	%rbp
	.cfi_def_cfa_offset 8
	retq
.Lfunc_end0:
	.size	_Z10select_GPUv, .Lfunc_end0-_Z10select_GPUv
	.cfi_endproc
                                        # -- End function
	.globl	main                            # -- Begin function main
	.type	main,@function
main:                                   # @main
	.cfi_startproc
# %bb.0:
	pushq	%rax
	.cfi_def_cfa_offset 16
	callq	_Z10select_GPUv
	xorl	%eax, %eax
	popq	%rcx
	.cfi_def_cfa_offset 8
	retq
.Lfunc_end1:
	.size	main, .Lfunc_end1-main
	.cfi_endproc
                                        # -- End function
	.type	.L.str,@object                  # @.str
	.section	.rodata.str1.1,"aMS",@progbits,1
.L.str:
	.asciz	"nvidia-smi &> /dev/null"
	.size	.L.str, 24

	.type	.L.str.1,@object                # @.str.1
.L.str.1:
	.asciz	"r"
	.size	.L.str.1, 2

	.type	.L.str.2,@object                # @.str.2
.L.str.2:
	.asciz	"Index of the GPU with the lowest temperature: %d (%d C)\n"
	.size	.L.str.2, 57

	.type	__hip_cuid_,@object             # @__hip_cuid_
	.bss
	.globl	__hip_cuid_
__hip_cuid_:
	.byte	0                               # 0x0
	.size	__hip_cuid_, 1

	.ident	"AMD clang version 18.0.0git (https://github.com/RadeonOpenCompute/llvm-project roc-6.3.2 25012 e5bf7e55c91490b07c49d8960fa7983d864936c4)"
	.section	".note.GNU-stack","",@progbits
	.addrsig
	.addrsig_sym __hip_cuid_

	.text
	.p2alignl 7, 3214868480
	.fill 96, 4, 3214868480
	.type	__hip_cuid_,@object             ; @__hip_cuid_
	.section	.bss,"aw",@nobits
	.globl	__hip_cuid_
__hip_cuid_:
	.byte	0                               ; 0x0
	.size	__hip_cuid_, 1

	.ident	"AMD clang version 18.0.0git (https://github.com/RadeonOpenCompute/llvm-project roc-6.3.2 25012 e5bf7e55c91490b07c49d8960fa7983d864936c4)"
	.section	".note.GNU-stack","",@progbits
	.addrsig
	.addrsig_sym __hip_cuid_
	.amdgcn_target "amdgcn-amd-amdhsa--gfx1100"
	.amdgpu_metadata
---
amdhsa.kernels:  []
amdhsa.target:   amdgcn-amd-amdhsa--gfx1100
amdhsa.version:
  - 1
  - 2
...

	.end_amdgpu_metadata
