我有一個memcpy問題,我似乎並不明白。我在一個線程上使用memcpy,與我從主體運行時相比,速度降低了3-4倍。在這兩種情況下,我有2個線程運行一個只等待和一個調用memcpy。你能給我任何可能的解釋嗎?我使用超線程的4核英特爾機器。memcpy在線程中調用的速度很慢
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <pthread.h>
#include <algorithm>
#define MILLION 1000000
#define START_TIMER(timer) { \
gettimeofday(&(timer), NULL); \
}
#define STOP_TIMER(timer) { \
gettimeofday(&(timer), NULL); \
}
#define TIME_DIFF(timer1, timer2, total) { \
long long sec_diff = 0; \
long long usec_diff = 0; \
sec_diff = (timer2).tv_sec - (timer1).tv_sec; \
usec_diff = (timer2).tv_usec - (timer1).tv_usec; \
(total)+= (sec_diff * MILLION) + usec_diff; \
}
void copy(){
struct timeval start, stop;
long long total=0;
char buff[1024*1024];
for(int i =0;i<100;i++){
char* temp = new char[1024*1024];
START_TIMER(start);
std::copy(buff,buff+1024*1024,temp);
STOP_TIMER(stop);
TIME_DIFF(start,stop,total);
delete temp;
}
printf("%lld\n",total/100);
}
void* mem(void* args){
copy();
pthread_exit(NULL);
}
void * nothing(void *args){
pthread_exit(NULL);
}
pthread_t thread;
int main(int argc,char* argv[]){
if(atoi(argv[1])==0){
pthread_create(&thread,NULL,nothing,NULL);
pthread_join(thread,NULL);
copy();
}
else{
pthread_create(&thread,NULL,mem,NULL);
pthread_join(thread,NULL);
}
}
謝謝你的時間。我希望這不是太愚蠢。
如果你在'i'循環之前初始化'buff',會發生什麼? – 1201ProgramAlarm
請分享您從main和thread調用複製函數的代碼。這樣我們可以嘗試重現問題。 – Sush
如果將main()中的copy()移動到線程創建之上,即先運行主線程副本,會發生什麼? – ThingyWotsit