Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix incorrect calculation of weighted average of elapsed time #209

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

chiayiz
Copy link

@chiayiz chiayiz commented Feb 24, 2023

Hello,

I found that timeval_factorial_average function calculated incorrect the average of the elapsed time, so I fixed it.

The original version calculates averages separately for seconds and microseconds.
This sometimes causes the average of X and X to be X-1 and the measured throughputs to be unstable.
I have even seen the total average time become negative.

This code below shows an example of the parameters that causes incorrect calculation.

#include <assert.h>
#include <stdio.h>
#include <sys/time.h>

typedef struct timeval timeval;

// original version
inline timeval timeval_factorial_average(timeval a, timeval b,
                                         unsigned int weight) {
  timeval tv;
  double factor = ((double)weight - 1) / weight;
  tv.tv_sec = factor * a.tv_sec + (double)b.tv_sec / weight;
  tv.tv_usec = factor * a.tv_usec + (double)b.tv_usec / weight;
  return (tv);
}

int main() {
  timeval x = {1677215184, 515990}; // Fri, 24 Feb 2023 05:06:24 GMT
  timeval y = timeval_factorial_average(x, x, 7); // y must be the same as x

  printf("x.tv_sec = %ld, x.tv_usec = %ld\n", x.tv_sec, x.tv_usec);
  printf("y.tv_sec = %ld, y.tv_usec = %ld\n", y.tv_sec, y.tv_usec);

  assert(x.tv_sec == y.tv_sec && x.tv_usec == y.tv_usec); // this assertion fails

  return 0;
}

Thank you.

@chiayiz chiayiz marked this pull request as ready for review February 24, 2023 06:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant