Measure execution time in CPU cycles?

Question:

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) 
Asked By: alphanumeric

||

Answers:

on linux systems you have time command, ie:

# time ls
/bin/ls ${=LS_OPTIONS}  0.00s user 0.00s system 68% cpu 0.003 total
Answered By: rsm

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}')
Answered By: surendra Allam
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.