#why using thread is slower?

8 messages · Page 1 of 1 (latest)

burnt finch
#

I want to learn multi-thread, then I copy some code from internet.

findOdd / findEven function means adding all odd/even number together

//using thread
int main(){
ull start=0, end =1900000000;
auto startTime =high_resolution_clock::now();

std::thread t1(findEven,start,end);
std::thread t2(findOdd,start,end);

t1.join();
t2.join();

auto stopTime=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stopTime-startTime);

cout<<OddSum<<"\n";
cout<<EvenSum<<"\n";
cout<<"duration: "<<float(duration.count())/1000000;

return 0;

}
// using thread end (It takes 16 second)

if not using thread,

findOdd(start,end);
findEven(start,end);

just use these code to replace. (It takes 2.6 seconds)

may I know why?

graceful baneBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

idle shore
#

for me it takes 1.29s with O3 with threads and 0.47 without

#

starting a thread does have overhead

#

so its likely not worth for small things

burnt finch
#

thank you

graceful baneBOT
#

@burnt finch Has your question been resolved? If so, run !solved :)

burnt finch
#

!solved