【发布时间】:2017-10-05 04:43:14
【问题描述】:
我对 memcpy 有一个问题,我似乎不明白。我在线程上使用 memcpy,与从主线程运行它时获得的时间相比,它慢了 3-4 倍。在这两种情况下,我都有 2 个线程在运行,一个正在等待,一个正在调用 memcpy。你能给我任何可能的解释吗?我使用具有超线程的 4 核 Intel 机器。
#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会发生什么? -
请分享您从 main 和线程调用复制函数的代码。这样我们就可以尝试重现问题。
-
如果将 main() 中的 copy() 移到 thread create 之上,即先运行主线程 copy,会发生什么?
-
Sush 复制功能就在 main 的上方。 @ThingyWotsit 只有一个线程会执行副本。您选择了哪一个作为执行参数。 0为主线程,其他为创建线程
标签: c++ c multithreading pthreads memcpy