Skip to content

Microsecond round up code doesn't round up. #12

@skliper

Description

@skliper

Describe the bug
Spawned from #1

The code comment claims it rounds up to never return zero. The formula implemented doesn’t actually round up in all cases, since generally when casting a float/double to an int you lose the fractional part (truncation, not rounding). So the code is not self-consistent. It’s not a POSIX or OS issue, it’s that the code doesn’t do what it says it does. The API document doesn’t specify a non-zero guarantee.

osal/src/os/posix/ostimer.c

Lines 284 to 290 in bfa7a33

/*
* Calculate microseconds per tick - Rounding UP
* - If the ratio is not an integer, this will choose the next higher value
* - The result is guaranteed not to be zero.
*/
OS_SharedGlobalVars.MicroSecPerTick = (1000000 + (OS_SharedGlobalVars.TicksPerSecond / 2)) /
OS_SharedGlobalVars.TicksPerSecond;

Similar misleading comment at:

osal/src/os/posix/ostimer.c

Lines 231 to 232 in bfa7a33

/* Round to the nearest microsecond */
POSIX_GlobalVars.ClockAccuracyNsec = (uint32)(clock_resolution.tv_nsec);

For what it’s worth, on Linux (our Ubuntu dev system) this code reports 100 ticks per second, and 10000 usec per tick. But if you pass in high values for ticks per second, it does return zero when it claims to round up (try 2000000 ticks per second).

To Reproduce
Steps to reproduce the behavior:

  1. Compile
#include <stdio.h>
void main()
{
  float num = 0.7;
  printf("float = %f, cast = %d\n", num, (int)num);
}
  1. Execute:
float = 0.700000, cast = 0

Expected behavior
Expected code to match comment, round up to not equal zero. Algorithm doesn't work as claimed in comment.

System observed on:

Additional context
Add any other context about the problem here.

Reporter Info
Jacob Hageman/NASA-GSFC

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions