0

I am working on a small, personal C++ project where I am interested in determining how many clock cycles have occurred in one hardware unit compared to another.

The speed of two units is known, and are always represented in MHz with a maximum of 2 decimal places. One unit can be seen as the controller of the other since it waiting for the other unit to complete its' task before the controller can move on. Mathematically, the calculation is pretty straightforward:

  1. Take the controller frequency and convert it to seconds/cycle via f = 1/s.
  2. Multiple this number by the elapsed number of controller cycles (Δcc * s/cc).
  3. Multiply this number by the frequency of the subject unit and you have how many subject clock cycles have occurred.

My concern here is with precision. I have thought of two possible approaches thusfar:

  1. Perform the math straight using doubles, or...
  2. Find the GCD between the two frequencies, perform the math around that frequency, and keep track of the time step with some unsigned integer within the subject.

My question to the stack overflow community is this: whether it's one of the above solutions or not, what would be the best solution for maintaining the greatest precision in this calculation? This calculation will be performed in a loop to determine when the controller can move along so it is important for the controller to know (in terms of its' own clock) whether or not the subject unit has completed its' task.

It is a safe assumption that neither of the two frequencies will ever exceed 500 MHz.

James B. Nall
  • 1,398
  • 3
  • 16
  • 27
  • In theory, maintaining the greatest precision can be maintained using arbitrary-precision arithmetic (see for example https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic). In practice, you just have to define what is your desired precision and act accordingly. You may use double, float, long long integer or anything else. There are ways of using everything of the mentioned above. – GMichael May 20 '16 at 09:05
  • what's wrong with this approach: `f1=432.12 MHz,f2=17.13 MHz. N1 = (43212 * N2) div 1713` and vice versa? – MBo May 20 '16 at 09:22
  • It depends on what you want to achieve sometimes you want to limit avg distortion from timing and sometimes the max distortions. So which one is it? also integer math is best for this ... you need just `+,-` and `compare` – Spektre May 20 '16 at 11:18
  • also see this [Question about cycle counting accuracy when emulating a CPU](http://stackoverflow.com/a/33317202/2521214) for additional concerns even if it is a bit different topic – Spektre May 20 '16 at 11:25

0 Answers0