How much overhead is there when creating a thread?

后端 未结 11 1369
故里飘歌
故里飘歌 2020-12-02 20:14

I just reviewed some really terrible code - code that sends messages on a serial port by creating a new thread to package and assemble the message in a new thread for every

11条回答
  •  天命终不由人
    2020-12-02 20:27

    It is indeed very system dependent, I tested @Nafnlaus code:

    #include 
    
    int main(int argc, char** argv)
    {
      for (volatile int i = 0; i < 500000; i++)
        std::thread([](){}).detach();
      return 0;
    }
    

    On my Desktop Ryzen 5 2600:

    windows 10, compiled with MSVC 2019 release adding std::chrono calls around it to time it. Idle (only Firefox with 217 tabs):

    It took around 20 seconds (20.274, 19.910, 20.608) (also ~20 seconds with Firefox closed)

    Ubuntu 18.04 compiled with:

    g++ main.cpp -std=c++11 -lpthread -O3 -o thread
    

    timed with:

    time ./thread
    

    It took around 5 seconds (5.595, 5.230, 5.297)

    The same code on my raspberry pi 3B compiled with:

    g++ main.cpp -std=c++11 -lpthread -O3 -o thread
    

    timed with:

    time ./thread
    

    took around 15 seconds (16.225, 14.689, 16.235)

提交回复
热议问题