首页 > 代码库 > double、float,哪个更快?

double、float,哪个更快?

    假设精度足够的情况下,double和float哪个更快?

    有人说,float更快,因为需要处理的数据量少,有人说,double快,因为最终CPU在进行计算时需要先把float转换为double。真相如何呢?

    VC++的编译器设置里有三种浮点模型,这三种浮点模型有什么区别呢?对运算速度又有什么影响呢?

 

    测试环境:Visual Studio 2013 update2,Intel(R) Core(TM) i5-2320 CPU @ 3.00GHz

    测试代码:

#include "stdafx.h"
#include <Windows.h>
#include <math.h>

int _tmain(int argc, _TCHAR* argv[])
{
    const int N = 50000000;
    LARGE_INTEGER start, end;

    //测试float
    float f1 = 12.0f;
    QueryPerformanceCounter((LARGE_INTEGER*)&start);
    for (int i = 0; i < N; i++)
    {
        f1 = sin(sqrt(exp(f1 * 2)));
    }
    QueryPerformanceCounter((LARGE_INTEGER*)&end);

    printf("float --->%f, %ld\r\n", f1, end.QuadPart - start.QuadPart);

    //测试double
    double f2 = 12.0;
    QueryPerformanceCounter((LARGE_INTEGER*)&start);
    for (int i = 0; i < N; i++)
    {
        f2 = sin(sqrt(exp(f2 * 2)));
    }
    QueryPerformanceCounter((LARGE_INTEGER*)&end);
    printf("double --->%lf, %ld\r\n", f2, end.QuadPart - start.QuadPart);

    system("pause");

    return 0;
}

    测试结果:

/fp:precise

/fp:fast

/fp:strict

float 7779467
double 6824241

float 5541635
double 6428042

float 9438907
double 8601029

double、float,哪个更快?