一步一步炼代码之多线程篇(一)基础

学习多线程编程:

环境:linux

基础程序:测试并行<概念1>和并发<概念2>

  1 #include <stdio.h>
  2 #include <string.h>
  3 #include <time.h>
  4 #include <sys/time.h>
  5 #include <omp.h>
  6 #define MAX_VALUE 10000000
  7
  8 double _test(int value)
  9 {
 10   unsigned long long index;
 11   double result;
 12
 13   result = 0.0;
 14   for(index = value + 1; index < MAX_VALUE; index +=2 )
 15     result += 1.0 / index;
 16
 17   return result;
 18 }
 19
 20 int main()
 21 {
 22   unsigned long long index;
 23   struct timeval time1;
 24   struct timeval time2;
 25   struct timeval time_temp;
 26   double value1,value2;
 27   double result[2];
 28
 29   value1 = 0.0;
 30   gettimeofday(&time1,NULL);
 31   for(index = 1; index < MAX_VALUE; index ++)//这里为并发计算 尚未用多线程
 32     value1 += 1.0 / index;
 33   gettimeofday(&time_temp,NULL);
 34   time1.tv_sec = time_temp.tv_sec - time1.tv_sec;
 35   time1.tv_usec = time_temp.tv_usec - time1.tv_usec;
 36
 37   value2 = 0.0;
 38   memset(result , 0, sizeof(double) * 2);
 39   gettimeofday(&time2,NULL);
 40
 41 #pragma omp parallel for //多核并行计算 这里为2核
 42   for(index = 0; index < 2; index++)
 43     result[index] = _test(index);
 44
 45   gettimeofday(&time_temp,NULL);
 46   time2.tv_sec = time_temp.tv_sec - time2.tv_sec;
 47   time2.tv_usec = time_temp.tv_usec - time1.tv_usec;
 48
 49   printf("time1 = %u:%u,time2 = %u:%u\n",time1.tv_sec,time1.tv_usec,time2.tv_sec,time2.tv_usec);
 50   return 0;
 51 }



运行结果:

time1 = 1:4294458481,time2 = 0:1239675

time1 = 0:490269,time2 = 1:4294699209
time1 = 0:435294,time2 = 1:4294790711

time1 = 0:436248,time2 = 1:4294780986


结果描述:第一次运行 并发快,之后都是并行快。执行一些其他操作之后,再运行,重复这样的现象。
结果分析:未知


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值