CS 301 - Homework 6

Here are a bunch of programs that are much slower than they could be.  Using the "Time" mode of NetRun, speed each one up by a factor of 5 or more.  Be sure to keep the output exactly the same.
  1. Speed this program up by eliminating the divide. Keep the loop in place.
    int divby=128;
    int foo(void) {
    unsigned int i, sum=0, val=1024;
    for (i=0;i<val;i++) sum+=i>>7; /* FIX: shift is same as dividing by 128, but way cheaper */
    return sum;
    }
  2. Figure out why this is slow, and speed it up. You must leave the loop in place; but anything else is fair game.
    int get_thingy(void); /* prototype for routine below */
    inline int get_thingy(void) { /* FIX: declare subroutine *above* use, and make it "inline" */
    return 2;
    }

    int foo(void) {
    int i, sum=0, val=1024;
    for (i=0;i<val;i++) sum+=get_thingy();
    return sum;
    }

  3. Here's a C++ performance pitfall I've seen too many times. Don't mess with my_class.
    class my_class {
    public:
    int val;
    my_class() {val=1;}
    private:
    char scratch_data[0x54321];
    };

    int some_function(my_class &c /* FIX: pass by reference! */,int d) {
    return c.val+d;
    }

    int foo(void) {
    my_class c;
    return some_function(c,0x1234+sizeof(my_class));
    }
As usual, you'll turn these problem in by just naming them HW6_1, HW6_2, etc. in NetRun

Problems are due Monday, November 7, at Midnight. 

O. Lawlor, ffosl@uaf.edu
Up to: Class Site, CS, UAF