-1

I want to accurately measure time of a Python code, that crashes. I can use the time command for unix, but that isn't as precise as time.time module in Python

start = time.time()
assert(1 < 0)
print(time.time() - start)

The code -- above -- definitely doesn't work if executed as Python code (although inside a Python interpreter it works, but that isn't desirable) , I am asking if there is a work-around ?

Sahil
  • 80
  • 4

2 Answers2

1

You need to set a custom sys.excepthook function which will be called right before your program "crashes":

start = time.time()

def my_excepthook(type, value, traceback):
    end = time.time()
    print("Program crashed after", end - start, "seconds")
    sys.__excepthook__(type, value, traceback)  # Print error message

sys.excepthook = my_excepthook
Delgan
  • 18,571
  • 11
  • 90
  • 141
  • Is it possible to incorporate this in my Python itself (I am in a virtual environment) ? Great solution! – Sahil Aug 31 '19 at 20:20
  • @Sahil It's complicated... You better should put this code in a small module file like `crashtime.py` and import it anytime you want to measure the crash time by adding `import crashtime` at the start of your script. – Delgan Aug 31 '19 at 20:23
  • How would the variable `start` be defined in that case ? – Sahil Aug 31 '19 at 20:28
  • @Sahil the sam way: just add it at the start of `crashtime.py` and call `import crashtime` at the very start of your program. – Delgan Aug 31 '19 at 20:38
0

you can use try except:

start = time.time()
try:
    assert(1 < 0)
except:
    print(time.time() - start)
kederrac
  • 16,819
  • 6
  • 32
  • 55
  • This can be done, but say I want to do this for assertion errors inside TensorFlow which has tonnes of Assertions errors spread over exotic file locations. – Sahil Aug 31 '19 at 20:10
  • you can include all the code in a try except if is fine with you – kederrac Aug 31 '19 at 20:11
  • especially if you import form another module is more simple, you can take into consideration the case of a crash and do something – kederrac Aug 31 '19 at 20:13