我发现C和C#中的类似代码之间存在巨大的性能差异.
C代码是:
#include <stdio.h>
#include <time.h>
#include <math.h>
main()
{
int i;
double root;
clock_t start = clock();
for (i = 0 ; i <= 100000000; i++){
root = sqrt(i);
}
printf("Time elapsed: %f\n", ((double)clock() - start) / CLOCKS_PER_SEC);
}
而C#(控制台应用程序)是:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
DateTime startTime = DateTime.Now;
double root;
for (int i = 0; i <= 100000000; i++)
{
root = Math.Sqrt(i);
}
TimeSpan runTime = DateTime.Now - startTime;
Console.WriteLine("Time elapsed: " + Convert.ToString(runTime.TotalMilliseconds/1000));
}
}
}
使用上面的代码,C#在0.328125秒(发布版本)内完成,而C#运行需要11.14秒.
C正在使用mingw编译成Windows可执行文件.
我一直认为C/C++更快,或者至少与C#相当.网到底是什么导致C代码运行速度慢了30倍?
编辑:
现在的结果是:
C仍然需要更长的时间,但这是可以接受的.