c# - Why does multithreading give a worse performance here? -
i enumerate through bitarray setting every second bit false.
now i'd speed splitting 2 threads.. weird reason though, time per thread half amount of work takes 64% more time, , wonder why's that?
could due kind of cpu caching effect? how do properly?
i have tried 8 threads lambda expressions around ~1400 ms, in single threading constandly got 850 ms. when let single thread work, took me 830 ms. don't understand, knowing cause here?
code:
class program { static int count = 0x10000000; static int half = count / 2; static bitarray bitarray = new bitarray(count); static unsafe void main(string[] args) { stopwatch sw = stopwatch.startnew(); #if single (int = 0; < bitarray.count; += 2) bitarray.set(i, true); #else thread thread1 = new thread(thread1); thread thread2 = new thread(thread2); thread1.start(); thread2.start(); thread1.join(); thread2.join(); #endif sw.stop(); console.writeline(sw.elapsedmilliseconds); console.readline(); } static void thread1() { stopwatch sw = stopwatch.startnew(); (int = 0; < half; += 2) bitarray.set(i, true); sw.stop(); console.writeline("thread1: {0}", sw.elapsedmilliseconds); } static void thread2() { stopwatch sw = stopwatch.startnew(); (int = half; < count; += 2) bitarray.set(i, true); sw.stop(); console.writeline("thread2: {0}", sw.elapsedmilliseconds); } }
bitarray not thread-safe class. should not use that. , in fact, beside correctness cause of slowness. here's why:
if @ source code of bitarray, contains int version
field, updated @ every operation, notably set()
, call.
this means every thread continuously updates same memory location, huge perf killer because cores have communicate , synchronize when accessing location. in condition makes perfect sense multithreaded solution has worse performance single core one.
Comments
Post a Comment