просто создавая поток, и объединение его замедляет выполнение основного потока на 50%. Как видно из приведенного ниже примера, нить ничего не делает и все еще оказывает существенное влияние на производительность. Я думал, что это может быть проблема с масштабированием мощности/частоты, поэтому я попытался спать после создания потока безрезультатно. Следующая программа, если скомпилирована с помощью
g++ -std=c++11 -o out thread_test.cpp -pthread
показывает результат
Before thread() trial 0 time: 312024526 ignore -1593025974
Before thread() trial 1 time: 243018707 ignore -494037597
Before thread() trial 2 time: 242929293 ignore 177714863
Before thread() trial 3 time: 242935290 ignore 129069571
Before thread() trial 4 time: 243113945 ignore 840242475
Before thread() trial 5 time: 242824224 ignore -1635749271
Before thread() trial 6 time: 242809490 ignore -1256215542
Before thread() trial 7 time: 242910180 ignore -555222712
Before thread() trial 8 time: 235645414 ignore 537501443
Before thread() trial 9 time: 235746347 ignore 118363977
After thread() trial 0 time: 567509646 ignore 223146324
After thread() trial 1 time: 476450035 ignore -393907838
After thread() trial 2 time: 476377789 ignore -1678874628
After thread() trial 3 time: 476377012 ignore -1015350122
After thread() trial 4 time: 476185152 ignore 2034280344
After thread() trial 5 time: 476420949 ignore -1647334529
After thread() trial 6 time: 476354679 ignore 441573900
After thread() trial 7 time: 476120322 ignore -1576726357
After thread() trial 8 time: 476464850 ignore -895798632
After thread() trial 9 time: 475996533 ignore -997590921
тогда как все испытания должны иметь одинаковую скорость.
EDIT: используйте rdtsc() для измерения времени, используйте большую продолжительность, используйте вычисленный результат
thread_test.cpp:
#include <ctime>
#include <thread>
#include <iostream>
int dorands(){
int a =0;
for(int i=0; i<10000000; i++){
a +=rand();
}
return a;
}
inline uint64_t rdtsc(){
uint32_t lo, hi;
__asm__ __volatile__ (
"xorl %%eax, %%eax\n"
"cpuid\n"
"rdtscp\n"
: "=a" (lo), "=d" (hi)
:
: "%ebx", "%ecx" );
return (uint64_t)hi << 32 | lo;
}
int foo(){return 0;}
int main(){
uint64_t begin;
uint64_t end;
for(int i = 0; i< 10; i++){
begin= rdtsc();
volatile int e = dorands();
end = rdtsc();
std::cout << "Before thread() trial "<<i<<" time: " << end-begin << " ignore " << e << std::endl;;
}
std::thread t1(foo);
t1.join();
for(int i = 0; i< 10; i++){
begin= rdtsc();
volatile int e = dorands();
end = rdtsc();
std::cout << "After thread() trial "<<i<<" time: " << end-begin << " ignore " << e << std::endl;;
}
return 1;
}