双倍性能比 C 中的浮点数快得多

Double performance a lot faster than floats in C

我试图弄清楚在 C 的某些代码中使用浮点数是否足以满足我的需要,但在搜索之后并没有真正理解如何将精度位转换为实际数字,我决定只写一点我的测试用例的代码,看看结果是什么。

浮点数似乎足够精确,但令我感到惊讶的是,在我的 17 4700hq haswell 处理器(windows 8.1 x64、C、MSVS v120)上,浮点数比 运行 长了大约 70%。我原以为 运行ning 时间会相似或浮点数执行得更快。但显然不是。所以我关闭了所有的优化,还是一样。在 debug 版本上试了一下,还是一样的性能问题。 AVX2 和 SSE 3,都在显示这个。

双打大约需要 197 秒到 运行 并漂浮 343 秒。

我已经浏览了英特尔® 64 和 IA-32 架构软件开发人员手册,但考虑到它的篇幅和我缺乏专业知识,我还没有从中收集到任何关于这个的答案。然后我看了一下两者的拆解,但我没有经过训练的眼睛发现任何明显的差异。

所以,有人知道为什么会这样吗?这是我使用的代码,除了 anError 变量之外,唯一的变化是从双精度到浮点数。

#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <omp.h>



int main( void ) {

    clock_t start = clock() ;

    // body of a candle
    double open = 0.500000 ;
    double close = 0.500001 ;
    double end = 1 ;

    uint64_t resultCounter = 0 ;
    double anError = 0 ;

    while (open < end){
        while(close < end){
            //calc # times result is postive. Should be 0.
            double res = open - close ;
            if (res > 0 ) { 
                resultCounter++ ; 
                if (anError < fabs( res )) { anError = res ;    }
            }
            close = close + 0.000001 ;
        }
        open = open + 0.000001 ;
        close = open + .000001 ;
    }

    clock_t finish = clock() ;
    double duration = ((double) (finish - start)) / CLOCKS_PER_SEC;
    double iterations = (((end - .50000) / .000001) * ((end - .50000) / .000001)) ;
    fprintf( stdout, "\nTotal processing time was %f seconds.\n", duration ) ;
    fprintf( stdout, "Error is %f. Number of times results were incorrect %llu out of %f iterations.\n", 
        anError, resultCounter, iterations ) ;

    return 0  ;
}

编辑:数字末尾缺少 f 似乎是原因(感谢 Joachim!)。显然,没有 f 后缀的 float 常量实际上是 double! C的另一个怪癖就是喜欢咬无知的屁股。不确定这种奇怪现象背后的基本原理是什么,但 耸耸肩 。如果有人想对此写一个好的答案以便我可以接受,请随意。

根据 C 标准:

An unsuffixed floating constant has type double. If suffix is the letter f or F, the floating constant has type float. If suffix is the letter l or L, the floating constant has type long double

有关浮点常量的更多详细信息here。所以:

num 只是一个浮点数

float num = 1.0f;
float num = 1.0F;

a double 被转换为 float 并存储在 num

float num = 1.0;

一个 float 被转换为 double 并存储在 num

double num = 1.0f;
double num = 1.0F;

由于常量从 double 到 float 的转换涉及复制内存,因此使用 float 时性能更差。