Timing Quake III hack 仅在使用优化编译时才有效

如何解决Timing Quake III hack 仅在使用优化编译时才有效

所以我刚刚发现了非常有趣的 Quake III 平方根倒数技巧。在了解了它的工作原理之后,我决定测试它。我发现该 hack 在启用优化的情况下编译时仅优于 math.h 1/sqrt(X)。

黑客的实现:

float q_sqrt(float x) {
    float x2 = x * 0.5F;
    int i = *( int* )&x;                  // evil floating point bit hack
    i = 0x5f3759df - (i >> 1);            // what the fuck?
    x = *( float* )&i;
    x = x * ( 1.5F - ( (x2 * x * x) ) );  //1st iteration
  //y = y * ( 1.5F - ( (x2 * y * y) ) );  //2nd iteration,can be removed
    return x;
}

要测试 1/sqrt(x) 与 q_sqrt(x) 相比的运行速度:

//qtest.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

/*
Implementation of 1/sqrt(x) used in tue quake III game
*/
float q_sqrt(float x) {
    float x2 = x * 0.5F;
    int i = *( int* )&x;                  // evil floating point bit hack
    i = 0x5f3759df - (i >> 1);            // what the fuck?
    x = *( float* )&i;
    x = x * ( 1.5F - ( (x2 * x * x) ) );  //1st iteration
  //y = y * ( 1.5F - ( (x2 * y * y) ) );  //2nd iteration,can be removed
    return x;
}


int main(int argc,char *argv[]) {
    struct timespec start,stop;
    //Will work on floats in the range [0,100]
    float maxn = 100;
    //Work on 10000 random floats or as many as user provides
    size_t num = 10000;
    //Bogus
    float ans = 0;
    //Measure nanoseconds
    size_t ns = 0;
    if (argc > 1)
        num = atoll(argv[1]);
    if (num <= 0) return -1;
    //Compute "num" random floats 
    float *vecs = malloc(num * sizeof(float));
    if (!vecs) return -1;
    for (int i = 0; i < num; i++)
        vecs[i] = maxn * ( (float)rand() / (float)RAND_MAX );

    fprintf(stderr,"Measuring 1/sqrt(x)\n");
    clock_gettime( CLOCK_REALTIME,&start);
    for (size_t i = 0; i < num; i++)
        ans += 1 / sqrt(vecs[i]);
    clock_gettime( CLOCK_REALTIME,&stop);
    ns = ( stop.tv_sec - start.tv_sec ) * 1E9 + ( stop.tv_nsec - start.tv_nsec );
    fprintf(stderr,"1/sqrt(x) took %.6f nanosecods\n",(double)ns/num );


    fprintf(stderr,"Measuring q_sqrt(x)\n");
    clock_gettime( CLOCK_REALTIME,&start);
    for (size_t i = 0; i < num; i++)
        ans += q_sqrt(vecs[i]);
    clock_gettime( CLOCK_REALTIME,"q_sqrt(x) took %.6f nanosecods\n",(double)ns/num );

    //Side by side
  //for (size_t i = 0; i < num; i++)
  //    fprintf(stdout,"%.6f\t%.6f\n",1/sqrt(vecs[i]),q_sqrt(vecs[i]));
    free(vecs);
}

在我的系统 (Ryzen 3700X) 上,我得到:

gcc -Wall -pedantic -o qtest qtest.c -lm
./qtest
Measuring 1/sqrt(x)
1/sqrt(x) took 4.470000 nanosecods
Measuring q_sqrt(x)
q_sqrt(x) took 4.859000 nanosecods


gcc -Wall -pedantic -O1 -o qtest qtest.c -lm
./qtest
Measuring 1/sqrt(x)
1/sqrt(x) took 0.378000 nanosecods
Measuring q_sqrt(x)
q_sqrt(x) took 0.497000 nanosecods


gcc -Wall -pedantic -O2 -o qtest qtest.c -lm
qtest.c: In function ‘q_sqrt’:
qtest.c:11:14: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
  11 |     int i = *( int* )&x;                  // evil floating point bit hack
     |
qtest.c:13:10: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
  13 |     x = *( float* )&i;
     |
./qtest
Measuring 1/sqrt(x)
1/sqrt(x) took 0.500000 nanosecods
Measuring q_sqrt(x)
q_sqrt(x) took 0.002000 nanosecods

我的期望是 q_sqrt(x) 比 1/sqrt(X) 开箱即用。阅读更多内容后,我现在知道要么libm 优化得更好,要么我的CPU 配备了sqrt(X) 的硬件解决方案。毕竟,自从快速逆根黑客开发以来,CPU 已经发生了突飞猛进的变化。

我不明白的是编译器会应用什么类型的优化来使它更快。当然,也许我的基准是构思错误的?

感谢您的帮助!!

解决方法

正如您所说,大多数现代 CPU 都包含一个浮点单元,该单元通常提供计算平方根的硬件指令。 FPU 还提供除法指令,因此我希望您的处理器(尽管我不知道)能够仅用几条汇编指令来计算逆 sqrt。您的结果有点令人惊讶:您应该检查是否真的使用了 FPU。我不了解锐龙,但在 ARM 处理器上,您可以编译软件以使用硬件浮点指令或软件库。

现在回答您的问题:GCC 优化是一个复杂的故事,通常不可能准确预测给定级别对性能的影响。所以像你一样运行一些测试,或者看看here的理论。

,

CLang/LLVM 的具体区别是这些。

没有优化(-O0):

q_sqrt(float):                             # @q_sqrt(float)
        push    rbp
        mov     rbp,rsp
        movss   dword ptr [rbp - 4],xmm0
        movss   xmm0,dword ptr [rip + .LCPI0_1] # xmm0 = mem[0],zero,zero
        mulss   xmm0,dword ptr [rbp - 4]
        movss   dword ptr [rbp - 8],xmm0
        mov     eax,dword ptr [rbp - 4]
        mov     dword ptr [rbp - 12],eax
        mov     ecx,dword ptr [rbp - 12]
        sar     ecx,1
        mov     eax,1597463007
        sub     eax,ecx
        mov     dword ptr [rbp - 12],eax
        movss   xmm0,dword ptr [rbp - 12]      # xmm0 = mem[0],zero
        movss   dword ptr [rbp - 4],dword ptr [rbp - 4]       # xmm0 = mem[0],zero
        movss   xmm2,dword ptr [rbp - 8]       # xmm2 = mem[0],zero
        mulss   xmm2,dword ptr [rbp - 4]
        mulss   xmm2,dword ptr [rbp - 4]
        movss   xmm1,dword ptr [rip + .LCPI0_0] # xmm1 = mem[0],zero
        subss   xmm1,xmm2
        mulss   xmm0,xmm1
        movss   dword ptr [rbp - 4],zero
        pop     rbp
        ret

优化(-Ofast):

q_sqrt(float):                             # @q_sqrt(float)
        movd    eax,xmm0
        sar     eax
        mov     ecx,1597463007
        sub     ecx,eax
        movd    xmm1,ecx
        mulss   xmm0,dword ptr [rip + .LCPI0_0]
        movdqa  xmm2,xmm1
        mulss   xmm2,xmm1
        mulss   xmm0,xmm2
        addss   xmm0,dword ptr [rip + .LCPI0_1]
        mulss   xmm0,xmm1
        ret

您可以使用 https://godbolt.org/ 来检查编译器的汇编输出,使用各种不同的标志并检查它如何影响输出。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-