Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is this Calculation working?

I have come across this piece of code where nanoseconds since the epoc and since boot has been calculated but I didn't get how?

http://code.metager.de/source/xref/cloudius-systems/osv/arch/aarch64/arm-clock.cc#61

 s64 arm_clock::uptime()  
{
    u64 cntvct;
    asm volatile ("isb; mrs %0, cntvct_el0; isb; " : "=r"(cntvct) :: "memory");

    cntvct = ((__uint128_t)cntvct * NANO_PER_SEC) / this->freq_hz;
    return cntvct; 
}

CNTVCT is cyclic counter register, why is the value of this register divided by CPU frequency and then multiplied by NANO_PER_SEC?

Also, how can Time of day be derived from these nanoseconds?

like image 395
Amit Singh Tomar Avatar asked Oct 18 '25 01:10

Amit Singh Tomar


1 Answers

why is the value of this register divided by CPU frequency and then multiplied by NANO_PER_SEC?

It is to convert units

CNTVCT is incremented each clock cycle

Frequency is clock cycles per second

NANO_PER_SEC is nanoseconds per second

so looking at the units of:

CNTVCT * NANO_PER_SEC
-------------
frequency   

they are:

clocks * nano/sec
------------------------
clocks/sec

equals (multiplying numerator and denominator by sec)

clocks * nano
-------------
clocks

equals (dividing numerator and denominator by clocks)

nano

so you need to divide by frequency to get seconds and multiply by nano to make it nano seconds

Also, how can Time of day be derived from these nanoseconds?

the nanoseconds is since boot time, not the epoch

But, you can get the current time of day, subtract the current nanoseconds, and then adjust by the nanoseconds going forward

like image 83
Glenn Teitelbaum Avatar answered Oct 19 '25 14:10

Glenn Teitelbaum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!