How long does thread creation and termination take under Windows?

前端 未结 3 670
长情又很酷
长情又很酷 2020-12-15 18:31

I\'ve split a complex array processing task into a number of threads to take advantage of multi-core processing and am seeing great benefits. Currently, at the start of the

3条回答
  •  情深已故
    2020-12-15 18:59

    I wrote this quite a while ago when I had the same basic question (along with another that will be obvious). I've updated it to show a little more about not only how long it takes to create threads, but how long it takes for the threads to start executing:

    #include 
    #include 
    #include 
    #include 
    
    const int num_threads = 32;
    
    const int switches_per_thread = 100000;
    
    DWORD __stdcall ThreadProc(void *start) {
        QueryPerformanceCounter((LARGE_INTEGER *) start);
        for (int i=0;i start_times(num_threads);
    
        LARGE_INTEGER l;
        QueryPerformanceCounter(&l);
    
        clock_t create_start = clock();
        for (int i=0;i

    Sample results:

    Milliseconds to create thread: 0.015625
    Microseconds per thread switch: 0.0479687
    

    The first few thread start times look like this:

    0.0632517 ms
    0.117348 ms
    0.143703 ms
    0.18282 ms
    0.209174 ms
    0.232478 ms
    0.263826 ms
    0.315149 ms
    0.324026 ms
    0.331516 ms
    0.3956 ms
    0.408639 ms
    0.4214 ms
    

    Note that although these happen to be monotonically increasing, that's not guaranteed (though there is definitely a trend in that general direction).

    When I first wrote this, the units I used made more sense -- on a 33 MHz 486, those results weren't tiny fractions like this. :-) I suppose someday when I'm feeling ambitious, I should rewrite this to use std::async to create the threads and std::chrono to do the timing, but...

提交回复
热议问题