mercredi 16 avril 2014

The worst optimization I ever made….

As a programmer I often try to simplify the code and reduce the number of operation, but few days ago I made a big mistake.

In a video processing system, I replaced the following line, we use for each frame to compute its Presentation TimeStamp (a.k.a its PTS):

curr_pts = first_pts + nb_frame * duration;

by a simple addition

curr_pts += duration;
and curr_pts was initialized with first_pts.

Now let say that all those values are floating point number (double or float).
In the floating point number world, those 2 code aren’t really equivalent due to the error accumulation.

That problem is well known and a solution to minimize the error is the Kahan’s summation algorithm.

Take a look here on Ideone at a small test code I made to demonstrate it…..

But basically if we compute the delta between the 1st version and the 2nd version, we get 3.14042e-05 and with the Kahan’s algorithm we get only a delta of 1.74623e-09.

A big mistake and a big reminder that floating point computation aren’t so easy ….

Aucun commentaire :

Enregistrer un commentaire