Linux下gcc编译的C程序的速度非常慢

时间:2018-10-16 21:37:19

标签: c linux gcc

我的PC上有两个装有i7-3770 @ 3.40 GHz的操作系统。一个操作系统是最新的Linux Kubuntu 18.04,另一个操作系统是在同一HDD上运行的Windows 10 Pro。

我已经测试了一个用C语言编写的简单有趣的程序,该程序根据数论进行了一些算术运算。在使用gcc 7.3.0编译的Kubuntu上,在Windows上使用gcc 5.2.0编译的上。由MinGW-W64项目构建。

结果令人惊讶,Linux上运行的程序比Windows慢4倍。

在Windows上,经过时间仅为6秒。在Linux上耗时24秒!在同一硬件上。

我尝试在Kubuntu上编译一些特定于CPU的选项,例如“ gcc -corei7”等,但没有任何帮助。在程序中使用了“ math.h”库,因此在两个系统上都使用“ -lm”完成了编译。源代码是相同的。

在Linux下出现这种速度慢是否有原因?

此外,我还在带有gcc 7.3.0的Linux Mint 19上的Core Duo T2250 @ 1.73 GHz的旧32位计算机上也编译了相同的代码。经过时间为28秒!与在Linux下以双倍频率运行的64位计算机相差无几。

下面是源代码,您可以对其进行编译和测试。

/* Program for playing with sigma(n) and tau(n) functions */
/* Compilation of code: "gcc name.c -o name -lm"             */ 

#include <stdio.h>
#include <math.h>
#include <time.h>

int main(void)
{
double i, nq, x, zacatek, konec, p;       
double odx, soucet, delitel, celkem, ZM;
unsigned long cas1, cas2;

i=(double)0; soucet=(double)0; celkem=(double)0; nq=(double)0;

zacatek=(double)1; konec=(double)1000000; x=zacatek;

ZM=(double)16 / (double)10;

printf("\n Program for playing with sigma(n) and tau(n) functions \n");
printf("---------------------------------------------------------\n");
printf("Calculation is running in range from %.0lf to %.0lf\n\n\n", zacatek, konec);
printf("Finding numbers which have sigma(n)/n = %.3lf\n\n", ZM);

cas1=time(NULL); 

 while (x <= konec) {
  i=1; celkem=0; nq=0;
  odx=sqrt(x)+1;
  while (i <= odx) {   
     if (fmod(x, i)==0) {
     nq++;
     celkem=celkem+x/i+i;
     }
   i++;
   }    
   nq=2*nq-1;
   if ((odx-floor(odx))==0) {celkem=celkem-odx;}
   if (fabs(celkem - (ZM*x)) < 0.001) {
      printf("%.0lf has sum of all divisors = %.3lf times the number itself (%.0lf, %.0lf)\n", x, ZM, celkem, nq+1);
      }
   x++;
 }

cas2=time(NULL);

printf("\n\nProgram ended.\n\n");
printf("Elapsed time %lu seconds.\n\n", cas2-cas1);

return (0);
}

0 个答案:

没有答案
相关问题