Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure execution time in CPU cycles?

My laptop spent 1.3 seconds to complete the process posted below. The same code ran on another machine and the timing was different: 2.1 seconds. This is because another machine runs on different Operation System, it has different CPU, memory and etc.

I wonder if instead of timing the process in seconds there would be a way to measure CPU cycles it took for the computer to complete a given process. So if the same code is run on different machines the measurements taken would always result the same number, and the result would be something like: it took 10,000 CPU cycles for this process to complete....

import time
def run():
    for i in range(10000000):
        0+0
start_time = time.time()
run()
print 'processed in: %s sec'%(time.time() - start_time) 
like image 360
alphanumeric Avatar asked Jan 23 '26 06:01

alphanumeric


1 Answers

hwcounter could help.

from hwcounter import Timer, count, count_end
from time import sleep
from math import sqrt

start = count()
sqrt(144) / 12
elapsed = count_end() - start
print(f'elapsed cycles: {elapsed}')
like image 151
surendra Allam Avatar answered Jan 25 '26 19:01

surendra Allam