大家帮看看,怎么回事?Delphi竟比vc++还快
前天有一个求素数个数问题,用delphi7.0求得100000000以内素数用时21.234秒,为想更快一点,把代码变为C语言后用vc++6.0计算居然要27.578秒,故把代码贴出,大家帮忙查找原因?Delphi7.0代码:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,math;
type
TForm1 = class(TForm)
Label1: TLabel;
Edit1: TEdit;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var i, j, k, l,m,n,r:integer;
d,s:integer;
x,z,t,t1,t2: double;
a:array of integer;
ss:string;
begin
t1:=now;
ss:=trim(self.Edit1.Text );
if ss<>'' then n:=strtoint(ss) else n:=0;
setlength(a,n+1);
m:=0;s:=0;
if (n=2) then
begin
m:=1;a[m]:=2;s:=2;
end;
if (n=3) then
begin
m:=1;a[m]:=2;s:=2;
m:=2;a[m]:=3;s:=5;
end;
if (n>3) then
begin
m:=1;a[m]:=2;s:=2;
m:=2;a[m]:=3;s:=5;
for i:=4 to n do
begin
x:=i;z:=sqrt(x);l:=trunc(z)+1;k:=0;
for j:=1 to m do
begin
if (a[j]>l) then break;
r:=i mod a[j];
if (r = 0) then
begin
inc(k);break;
end;
end;
if (k = 0) then
begin
inc(m);
s := s + i;
a[m]:=i;
end;
end;
end;
t2:=now;
t:=(t2-t1)*86400;
ss:=floattostr(t);
self.Label5.Caption :=ss;
ss:=inttostr(m);
self.Label3.Caption :=ss;
end;
end.
vc++6.0代码:
// suhucs.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <malloc.h>
int main(int argc, char* argv[])
{
int i, j, k, l,m,n,r;
int d,s;
double x,z,t;
clock_t begin,end;
int *a;
printf("n=");
scanf("%d",&n);
printf("\n");
a=(int *)malloc((n+1)*sizeof(int)) ;
begin=clock();
m=0;s=0;
if(n==2)
{
m=1;a[m]=2;s=2;
}
if(n==3)
{
m=1;a[m]=2;s=2;
m=2;a[m]=3;s=5;
}
if(n>3)
{
m=1;a[m]=2;s=2;
m=2;a[m]=3;s=5;
for(i=4;i<=n;i++)
{
x=i;z=sqrt(x);l=(int)z+1;k=0;
for( j=1;j<= m;j++)
{
if(a[j]>l)break;
r=i%a[j];
if (r == 0) {
k++;break;
}
}
if (k == 0) {
m++;
s = s + i;
a[m]=i;
}
}
}
end=clock();
t=(double)(end-begin)/CLOCKS_PER_SEC;
printf("素数个数=%d\n",m);
printf("计算时间=%f",t);
free(a);
system("pause");
return 0;
}