2022-04-16 12:20:44 +00:00
import os
import re
import pickle
import numpy as np
from warnings import warn
def get_sample_of_gpu ( ) :
from re import sub , findall
import subprocess
from subprocess import run
no_graph = " NVIDIA-SMI has failed because it couldn ' t communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running. "
no_version = " Failed to initialize NVML: Driver/library version mismatch "
smi_string = run ( [ ' nvidia-smi ' ] , stdout = subprocess . PIPE )
smi_string = smi_string . stdout . decode ( ' utf-8 ' )
smi_string = smi_string . split ( " \n " )
2023-06-01 08:20:51 +00:00
smi_string = list ( filter ( lambda x : x , smi_string ) )
2022-04-16 12:20:44 +00:00
if smi_string [ 0 ] == no_graph :
raise Exception ( " It seems that no NVIDIA GPU is installed " )
elif smi_string [ 0 ] == no_version :
raise Exception ( " nvidia-smi version mismatch " )
else :
2023-06-01 08:20:51 +00:00
return findall ( " [0-9]*MiB | [0-9]*W " , smi_string [ 6 ] )
2022-04-16 12:20:44 +00:00
#for l in smi_string:
#temp = findall("[0-9]*MiB | [0-9]*W",l)
#if temp:
#return temp
2023-06-28 16:02:56 +00:00
2022-04-16 12:20:44 +00:00
def total_watt_consumed ( ) :
with open ( pickle_name , ' rb ' ) as f :
x = pickle . load ( f )
x = np . array ( x )
x = x [ : , 0 ]
y = [ int ( re . findall ( " \ d+ " , xi ) [ 0 ] ) for xi in x ]
return sum ( y )
2023-06-28 16:02:56 +00:00
2022-04-16 12:20:44 +00:00
if __name__ == ' __main__ ' :
dataDump = [ ]
#var = True
#pickling_on = open("wattdata.pickle","wb")
while True :
try :
dataDump . append ( get_sample_of_gpu ( ) )
with open ( pickle_name , ' wb ' ) as f :
pickle . dump ( dataDump , f )
except EOFError :
warn ( ' Pickle ran out of space ' )
2022-04-17 16:18:41 +00:00
size + = 0.01
2022-04-16 12:20:44 +00:00
finally :
2022-04-17 16:18:41 +00:00
f . close ( )
2022-04-16 12:20:44 +00:00
#if retcode == 0:
#break
#pickle.dump(dataDump, pickling_on)
#pickling_on.close()