Optimizing Code to less time complexity possible

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 446 Views - Last Post: 11 October 2019 - 08:16 PM Rate Topic: -----

#16 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7088
  • View blog
  • Posts: 24,090
  • Joined: 05-May 12

Re: Optimizing Code to less time complexity possible

Posted 11 October 2019 - 06:46 PM

The code in post #12 can be converted to use pointers. With old compilers this used to make a difference in terms of actual operations. With modern compilers, most of them automatically convert array indexing into pointer operations to get you the same number of actual operations. Some compilers are even so smart that you actually want to leave the array indexing code in place because it lets it figure out that it should use the vector operations supported by a lot of modern processors.

Anyway, here's a pointer equivalent:
#define MAX_SIZE 2000

extern short const_array[MAX_SIZE];

long fun(short x)
{
    static short buffer[MAX_SIZE] = { 0 };
    static short * bufferEnd = &buffer[MAX_SIZE];
    static short * head = buffer;
    static size_t count = 0; 

    if (head == buffer)
        head = bufferEnd;
    *(--head) = x;

    if (count < MAX_SIZE)
        count++;

    short * constElements = const_array;
    short * constElementsEnd = &const_array[count];
    short * bufferElements = head;
    long res = 0;
    while (constElements < constElementsEnd)
    {
        res += *bufferElements++ * *constElements++;
        if (bufferElements >= bufferEnd)
            bufferElements = buffer;
    }
    return res;
}


Was This Post Helpful? 0
  • +
  • -

#17 Salem_c   User is offline

  • void main'ers are DOOMED
  • member icon

Reputation: 2387
  • View blog
  • Posts: 4,522
  • Joined: 30-May 10

Re: Optimizing Code to less time complexity possible

Posted 11 October 2019 - 08:16 PM

Post a real-world test case of you calling fun() a few thousand times, and perhaps we can make a meaningful attempt at
  • guessing what your real question is ( http://xyproblem.info/ )
  • making improvements to your code
  • making a much better suggestion to begin with.

This post has been edited by Salem_c: 11 October 2019 - 08:18 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2