64位/32位 C++/C# 数学计算性能对比测试
在下面的网址:http://www.2cto.com/kf/201111/112209.html 看到了使用MS的CL、gcc、Intel的icl、PGI的pgcc及Codegear的bcc 几个不同编译器编译的C/C++ 程序性能对比,结论是Intel的编译器性能最高。
同样把这段Intel的SDK中的代码迁移到C#中比较一下
我的笔记本是:Intel Core4 P8700 2.53G的CPU,4G内存,Win7 64bit系统,VS2010自带的编译器
对于代码略作调整和注释
C++代码
01 //intel的性能测试例子
02 #include <stdio.h>
03 #include <stdlib.h>
04 #include <time.h>
05 #include <math.h>
06
07 //为cin cout 提供
08 #include <iostream>
09 using namespace std;
10
11 #define INTEG_FUNC(x) fabs(sin(x)) //计算公式
12
13 double dclock(void);
14
15 int main(void)
16 {
17 unsigned int i, j, N;
18 double step, x_i, sum;
19 double start, finish, duration, clock_t;
20 double interval_begin = 0.0;
21 double interval_end = 2.0 * 3.141592653589793238;
22
23 start = clock(); //初始时间
24
25 printf(" /n");
26 printf(" Number of中文| Computed Integral | /n"); //Win7下中文显示正常
27 printf(" Interior Points | | /n");
28
29 for (j=2;j<27;j++)
30 {
31 N = 1 << j;
32
33 step = (interval_end - interval_begin) / N;
34 sum = INTEG_FUNC(interval_begin) * step / 2.0;
35
36 for (i=1;i<N;i++)
37 {
38 x_i = i * step;
39 sum += INTEG_FUNC(x_i) * step;
40 }
41
42 sum += INTEG_FUNC(interval_end) * step / 2.0;
43
44 //printf(" %10d | %14e | /n", N, sum);
45 printf(" %14e /n", sum);
46 }
47
48 finish = clock(); //结束时间
49 duration = (finish - start);
50 printf(" /n");
51 printf(" Application Clocks = %10e /n", duration);
52 printf(" /n");
53
54 int tempA;
55 cin>>tempA;
56
57 return 0;
58 }
默认编译参数,都是Release编译后,拿出exe文件独立运行
32bit C++ 6338ms
C# 代码
01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Text;
05
06 namespace ConsoleApplication1
07 {
08 class Program
09 {
10 static void Main(string[] args)
11 {
12 int time = System.Environment.TickCount; //添加计时器
13
14 #region
15 int i, j, N;
16 double step, x_i, sum;
17 double start, finish, duration, clock_t;
18 double interval_begin = 0.0;
19 double interval_end = 2.0 * 3.141592653589793238;
20
21 for (j = 2; j < 27; j++)
22 {
23 N = 1 << j;
24 step = (interval_end - interval_begin) / N;
25 sum = Math.Abs(Math.Sin(interval_begin)) * step / 2.0;
26
27 for (i = 1; i < N; i++)
28 {
29 x_i = i * step;
30 sum += Math.Abs(Math.Sin(x_i)) * step;
31 }
32
33 sum += Math.Abs(Math.Sin(interval_end)) * step / 2.0;
34 Console.Write(sum.ToString()+"/r/n");
35 }
36
37 Console.Write((System.Environment.TickCount - time).ToString());
38 Console.ReadLine();
39 #endregion
40 }
41 }
42 }
32bit C# 命令行 5382ms
32bit C# WinForm 5351ms
都是重复测试了5次,最大最小误差少于30ms
从左到依次为:32bit C++、32bit C#命令行、32bit C#WinForm
C#的竟然比C++快了1秒。
再看看64bit的,64bit C++ 3696ms,64bit C# 5382 ms
从左到右依次为:
64bit C++,32bitC++,64bit C#
可见该程序64bit 编译时,C++的性能大幅提升,C#的几乎不变。
两个计算精度应该相同,C++是因为输出的格式科学计数法隐藏了后面的小数
结论:
1. C# 在WinForm和命令行中,数学计算性能相当
2. 32bit下C#的性能还不错,若能在64bit下编译器也能充分优化达到C++那样的提升就好了。
杨韬的学习备忘录YTYT2002YTYT
http://www.cnblogs.com/ytyt2002ytyt/archive/2011/11/24/2261104.html