Will multi threading provide any performance boost?

前端 未结 19 821
说谎
说谎 2021-02-05 13:49

I am new to programming in general so please keep that in mind when you answer my question.

I have a program that takes a large 3D array (1 billion elements) and sums up

相关标签:
19条回答
  • 2021-02-05 14:18

    There is only one way to optimize code: figure out what you're doing that's slow, and do less of it. A special case of "doing less of it" is to do something else instead that's faster.

    So first of all, here's what I'm doing based on your posted code:

    #include <fstream>
    #include <sstream>
    using std::ios_base;
    
    template<typename Iterator, typename Value>
    void iota(Iterator start, Iterator end, Value val) {
        while (start != end) {
            *(start++) = val++;
        }
    }
    
    int main() {
    
        const int dim = 1000;
        const int cubesize = dim*dim*dim;
        const int squaresize = dim*dim;
        const int steps = 7; //ranges from 1 to  255
        typedef unsigned char uchar;
    
        uchar *partMap = new uchar[cubesize];
        // dummy data. I timed this separately and it takes about
        // a second, so I won't worry about its effect on overall timings.
        iota(partMap, partMap + cubesize, uchar(7));
        uchar *projection = new uchar[squaresize];
    
        for (int stage = 1; stage < steps; stage++) {
            for (int j = 0; j < dim; j++) {
                    for (int i = 0; i < dim; i++)
                    {
                            int sum = 0;
                            for (int k = 0; k < dim; k++)
                                if (partMap[(((i * dim) + k) * dim) + j] >= stage)
                                    sum++;
    
                            projection[(j*dim) + i] = sum;
                    }
            }
    
            std::stringstream filename;
            filename << "results" << stage << ".bin";
            std::ofstream file(filename.str().c_str(), 
                ios_base::out | ios_base::binary | ios_base::trunc);
            file.write((char *)projection, squaresize);
        }
    
        delete[] projection;
        delete[] partMap;
    }
    

    (Edit: just noticed that "projection" should be an array of int, not uchar. My bad. This will make a difference to some of the timings, but hopefully not too big of one.)

    Then I copied result*.bin to gold*.bin, so I can check my future changes as follows:

    $ make big -B CPPFLAGS="-O3 -pedantic -Wall" && time ./big; for n in 1 2 3 4 5
    6; do diff -q results$n.bin gold$n.bin; done
    g++  -O3 -pedantic -Wall   big.cpp   -o big
    
    real    1m41.978s
    user    1m39.450s
    sys     0m0.451s
    

    OK, so 100 seconds at the moment.

    So, speculating that it's striding through the billion-item data array that's slow, let's try only going through once, instead of once per stage:

        uchar *projections[steps];
        for (int stage = 1; stage < steps; stage++) {
             projections[stage] = new uchar[squaresize];
        }
    
        for (int j = 0; j < dim; j++) {
                for (int i = 0; i < dim; i++)
                {
                        int counts[256] = {0};
                        for (int k = 0; k < dim; k++)
                                counts[partMap[(((i * dim) + k) * dim) + j]]++;
    
                        int sum = 0;
                        for (int idx = 255; idx >= steps; --idx) {
                            sum += counts[idx];
                        }
                        for (int stage = steps-1; stage > 0; --stage) {
                            sum += counts[stage];
                            projections[stage][(j*dim) + i] = sum;
                        }
                }
        }
    
        for (int stage = 1; stage < steps; stage++) {
            std::stringstream filename;
            filename << "results" << stage << ".bin";
            std::ofstream file(filename.str().c_str(),
                ios_base::out | ios_base::binary | ios_base::trunc);
            file.write((char *)projections[stage], squaresize);
        }
    
        for (int stage = 1; stage < steps; stage++) delete[] projections[stage];
        delete[] partMap;
    

    It's a bit faster:

    $ make big -B CPPFLAGS="-O3 -pedantic -Wall" && time ./big; for n in 1 2 3 4 5
    6; do diff -q results$n.bin gold$n.bin; done
    g++  -O3 -pedantic -Wall   big.cpp   -o big
    
    real    1m15.176s
    user    1m13.772s
    sys     0m0.841s
    

    Now, steps is quite small in this example, so we're doing a lot of unnecessary work with the "counts" array. Without even profiling, I'm guessing that counting to 256 twice (once to clear the array and once to sum it) is quite significant compared with counting to 1000 (to run along our column). So let's change that:

        for (int j = 0; j < dim; j++) {
                for (int i = 0; i < dim; i++)
                {
                        // steps+1, not steps. I got this wrong the first time,
                        // which at least proved that my diffs work as a check
                        // of the answer...
                        int counts[steps+1] = {0};
                        for (int k = 0; k < dim; k++) {
                            uchar val = partMap[(((i * dim) + k) * dim) + j];
                            if (val >= steps) 
                                counts[steps]++;
                            else counts[val]++;
                        }
    
                        int sum = counts[steps];
                        for (int stage = steps-1; stage > 0; --stage) {
                            sum += counts[stage];
                            projections[stage][(j*dim) + i] = sum;
                        }
                }
        }
    

    Now we're only using as many buckets as we actually need.

    $ make big -B CPPFLAGS="-O3 -pedantic -Wall" && time ./big; for n in 1 2 3 4 5
    6; do diff -q results$n.bin gold$n.bin; done
    g++  -O3 -pedantic -Wall   big.cpp   -o big
    
    real    0m27.643s
    user    0m26.551s
    sys     0m0.483s
    

    Hurrah. The code is nearly 4 times as fast as the first version, and produces the same results. All I've done is change what order the maths is done: we haven't even looked at multi-threading or prefetching yet. And I haven't attempted any highly technical loop optimisation, just left it to the compiler. So this can be considered a decent start.

    However it's still taking an order of magnitude longer than the 1s which iota runs in. So there are probably big gains still to find. One main difference is that iota runs over the 1d array in sequential order, instead of leaping about all over the place. As I said in my first answer, you should aim to always use sequential order on the cube.

    So, let's make a one-line change, switching the i and j loops:

                for (int i = 0; i < dim; i++)
        for (int j = 0; j < dim; j++) {
    

    This still isn't sequential order, but it does mean we're focussing on one million-byte slice of our cube at a time. A modern CPU has at least 4MB cache, so with a bit of luck we'll only hit main memory for any given part of the cube once in the entire program. With even better locality we could reduce the traffic in and out of L1 cache, too, but main memory is the slowest.

    How much difference does it make?

    $ make big -B CPPFLAGS="-O3 -pedantic -Wall" && time ./big; for n in 1 2 3 4 5
    6; do diff -q results$n.bin gold$n.bin; done
    g++  -O3 -pedantic -Wall   big.cpp   -o big
    
    real    0m8.221s
    user    0m4.507s
    sys     0m0.514s
    

    Not bad. In fact, this change alone brings the original code from 100s to 20s. So this is responsible for a factor of 5, and everything else I did is responsible for another factor of 5 (I think the difference between 'user' and 'real' time in the above is mostly accounted for by the fact my virus scanner is running, which it wasn't earlier. 'user' is how much time the program occupied a CPU, 'real' includes time spent suspended, either waiting on I/O or giving another process time to run).

    Of course, my bucket sort relies on the fact that whatever we're doing with the values in each column is commutative and associative. Reducing the number of buckets only worked because large values are all treated the same. This might not be true for all your operations, so you'll have to look at the inner loop of each one in turn to figure out what to do with it.

    And the code is a bit more complicated. Instead of running over the data doing "blah" for each stage, we're computing all the stages at the same time in a single run over the data. If you start doing row and column computations in a single pass, as I recommended in my first answer, this will get worse. You may have to start breaking your code into functions to keep it readable.

    Finally, a lot of my performance gain came from an optimisation for the fact that "steps" is small. With steps=100, I get:

    $ make big -B CPPFLAGS="-O3 -pedantic -Wall" && time ./big; for n in 1 2 3 4 5
    6; do diff -q results$n.bin gold$n.bin; done
    g++  -O3 -pedantic -Wall   big.cpp   -o big
    
    real    0m22.262s
    user    0m10.108s
    sys     0m1.029s
    

    This isn't so bad. With steps=100 the original code probably takes about 1400 seconds, although I'm not going to run it to prove that. But it's worth remembering that I haven't completely taken away the time dependency on "steps", just made it sub-linear.

    0 讨论(0)
  • 2021-02-05 14:18

    Multithreading across multiple cores could reduce the time required to sum across the axes, but special care is required. You might actually get larger performance boosts from some changes you could make to your single thread code:

    1. You only need as many threads to match the number of cores available to you. This is a CPU intensive operation, and threads are unlikely to be waiting for I/O.

    2. The above assumption might not hold if the entire array does not fit in RAM. If portions of the array are paged in and out, some threads will be waiting for paging operations to complete. In that case, the program might benefit from having more threads than cores. Too many, however, and performance will drop due to the cost of context switching. You might have to experiment with the thread count. The general rule is to minimize the number of context switches between ready threads.

    3. If the entire array does not fit in RAM, you want to minimize paging! The order in which each thread accesses memory matters, as does the memory access pattern of all the running threads. To the extent possible, you would want to finish up with one part of the array before moving to the next, never to return to a covered area.

    4. Each core would benefit from having to access a completely separate region of memory. You want to avoid memory access delays caused by locks and bus contention. At least for one dimension of the cube, that should be straightforward: set each thread with its own portion of the cube.

    5. Each core would also benefit from accessing more data from its cache(s), as opposed to fetching from RAM. That would mean ordering the loops such that inner loops access nearby words, rather than skipping across rows.

    6. Finally, depending on the data types in the array, the SIMD instructions of Intel/AMD processors (SSE, at their various generations) can help accelerate single core performance by summing multiple cells at once. VC++ has some built in support.

    7. If you have to prioritize your work, you might want to first minimize disk paging, then concentrate on optimizing memory access to make use of the CPU caches, and only then deal with multithreading.

    0 讨论(0)
  • 2021-02-05 14:18

    How does your code work. Does it go like this?

    for each row: add up the values
    for each column: add up the values
    for each stack: add up the values
    

    If so, you might want to read up on "locality of reference". Depending how your data is stored, you might find that while you're doing the stacks, a whole cache line has to be pulled in for each value, because the values are nowhere near each other in memory. In fact, with a billion values, you could be pulling things all the way from disk. Sequential access with a long stride (distance between values) is the worst possible use for cache. Try profiling, and if you see that adding up the stacks is taking longer than adding up the rows, this is almost certainly why.

    I think you could be saturating the memory bus(*), in which case multithreading would only help if core2 quad uses different buses for different cores. But if you're not saturating the bus bandwidth, you can't get best performance this way even once you multi-thread. You'll have 4 cores spending all their time stalled on cache misses instead of one.

    If you are memory cache bound, then your goal should be to visit each page/line of memory as few times as possible. So I'd try things like running over the data once, adding each value to three different totals as you go. If that runs faster on a single core, then we're in business. The next step is that with a 1000x1000x1000 cube, you have 3 million totals on the go. That doesn't fit in cache either, so you have to worry about the same cache miss problems writing as you do reading.

    You want to make sure that as you run along a row of 1000 adjacent values in RAM adding to the row total that they all share, you're also adding to adjacent totals for the columns and stacks (which they don't store). So the "square" of column totals should be stored in the appropriate way, as should the "square" of stacks. That way you deal with 1000 of your billion values just by pulling about 12k of memory into cache (4k for 1000 values, plus 4k for 1000 column totals, plus 4k for 1000 stack totals). As against that, you're doing more stores than you would be by concentrating on 1 total at a time (which therefore could be in a register).

    So I don't promise anything, but I think it's worth looking at order of memory access, whether you multi-thread or not. If you can do more CPU work while accessing only a relatively small amount of memory, then you'll speed up the single-threaded version but also put yourself in much better shape for multi-threading, since the cores share a limited cache, memory bus, and main RAM.

    (*) Back of envelope calculation: in random random reviews off the internet the highest estimated FSB bandwidth for Core2 processors I've found so far is an Extreme at 12GB/s, with 2 channels at 4x199MHz each). Cache line size is 64 bytes, which is less than your stride. So summing a column or stack the bad way, grabbing 64 bytes per value, would only saturate the bus if it was doing 200 million values per second. I'm guessing it's nothing like this fast (10-15 seconds for the whole thing), or you wouldn't be asking how to speed it up.

    So my first guess was probably way off. Unless your compiler or CPU has inserted some very clever pre-fetching, a single core cannot be using 2 channels and 4 simultaneous transfers per cycle. For that matter, 4 cores couldn't use 2 channels and 4 simultaneous transfers. The effective bus bandwidth for a series of requests might be much lower than the physical limit, in which case you would hope to see good improvements from multi-threading simply because you have 4 cores asking for 4 different cache lines, all of which can be loaded simultaneously without troubling the FSB or the cache controller. But the latency is still the killer, and so if you can load less than one cache line per value summed, you'll do much better.

    0 讨论(0)
  • 2021-02-05 14:18

    Absolutely. At least getting each core on a thread to work on your problem concurrently will help. It's not clear if more threads would help, but it's possible.

    0 讨论(0)
  • 2021-02-05 14:20

    I think that even if multithreading can produce a performance boost it's the wrong way to approach optimization. Multiple cores are all the rage because they are the only way for CPU manufacturers to provide faster CPU speeds at a marketable rate -- not necessarily because they're an amazing programming tool (there's still a lot of maturing that needs to happen).

    Always look at the algorithm you're using above all else. You say your program is very RAM intensive -- what can you do to improve cache hits? Is there a way to sort your array so that the computations can be applied linearly? What programming language are you using and would it benefit you to optimize in a lower level language? Is there a way that you can use dynamic programming to store your results?

    In general, spend all your resources working toward a more efficient algorithm, mathematically and as compiler optimizations, then worry about multi-core. Of course, you may already be at that stage, in which case this comment isn't very useful ;p

    0 讨论(0)
  • 2021-02-05 14:20

    Your computer system typically has some elements that limit the rough performance. Which part is your limiting elements, depends on the concrete situation. Normally one of the following factors may be the cause of your performance problems.

    • Disk I/O bandwidth: In most enterprise applications the sheer size of data processed requires it to be stored in some database. Acessing this data may be slowed down by both: the maximum transfer speed, but very often the biggest impact will be caused by a big number of small disk accesses reading some blocks here and there. The you will see the latency time of the heads of the disks moving around and even the time the disk requires for a full rotation may limit your application. Long times ago i had a real problem using some expansive SUN E430 installation that was outperformed by my small NeXTstation... It was the constant fsync()ing of my database which was slowed down by disks not caching write accesses (for good reason). Normally you can speed up your system by adding additional disks to get more I/O per second. Dedicating your drives to specific tasks may even do better in some cases.

    • Network Latency: nearly everything that affects application speed said for disks is equivalent for Network I/O.

    • RAM: If your RAM is not big enough to store your complete application image you need to store it on an external disks. Therefore the Disk I/O slowdown bites you again.

    • CPU processing speed (either Integer or floating point): CPU processing power is the next factor that is a limit for CPU intensive tasks. A CPU has a physical speed limit that cannot be outreached. The only way to speed up is to add more CPU.

    These limits may help you to find an answer for your specific problem.

    Do you need simply more processing power and your system has more than one CPU or Core? In that case multithreading will improve your performance.

    Do you observe significant Network or Disk Latency? If you see this, your valuable CPU might throw away CPU cycles waiting for some slow I/O. If more that one thread is active, this thread might find all data required for processing in memory and could pick up these otherwise wasted CPU cycles.

    Therefore you need to observe your existing application. try to extimate the memory bandwidth of the data shuffled around. If the application is active on one CPU below 100%, you might have reached the memory bandwidth limit. In that case, additional threading will do no good for you because this does not give you mor bandwidth from memory.

    If the CPU is at 100%, give it a try, but have a look at the algorithms. Multi-threading will add additional overhead for synchronization (and complexity, tons of complexity) that might slightly reduce the memory bandwidth. Prefer alorithms that can be implemented avoiding fine grained synchronizations.

    If you see I/O wait times, think about clever partitioning or caching and then about threading. There is a reason why GNU-make supported parallel build back in the 90's :-)

    The problem domain you've described leads me to gav a look at clever algorithms first. Try to using sequential read/write operations on main memory as much as possible to support the CPU and memory subsystems as much as possible. Keep operations "local" and datastructures as small and optimzed as possible to reduce the amount of memory that needs to be shuffled around before switching to a second core.

    0 讨论(0)
提交回复
热议问题