C#/ XNA - 乘法比司更快? [英] C#/XNA - Multiplication faster than Division?

查看:153
本文介绍了C#/ XNA - 乘法比司更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了一个鸣叫最近,我感到困惑(这被张贴由XNA编码器,在写一个XNA游戏的上下文中):

I saw a tweet recently that confused me (this was posted by an XNA coder, in the context of writing an XNA game):

Microoptimization提示:如果可能的话,用乘法,而不是划分在高频领域。这是几个周期更快。

我很惊讶,因为我一直以为那里的编译器非常聪明的(例如,使用位移),以及最近阅读肖恩哈格里夫斯一个后说大同小异事情。我不知道有多少道理了。在这一点,因为有很多在我的游戏计算。

I was quite surprised, because I always thought compilers where pretty smart (for example, using bit-shifting), and recently read a post by Shawn Hargreaves saying much the same thing. I wondered how much truth there was in this, since there are lots of calculations in my game.

我问,希望能为样本,但是楼主无法举一个。他,然而,这样说:

I inquired, hoping for a sample, however the original poster was unable to give one. He did, however, say this:

不一定当它像中心=宽度/ 2。而且我已经确定了是的,这是值得的。 :)

所以,我很好奇...

So, I'm curious...

任何人都可以给出一些代码,你可以改变一个部门到一个乘法和获得的性能增益,其中C#编译器是不能做自己同样的事情的例子。

推荐答案

大多数编译器可以做的,当你给他们一个机会,优化合理的工作。例如,如果你划分的由一个常数的,机会是非常好的,所以它是关于尽快做的事情你可以合理替代它的编译器可以/将优化了。

Most compilers can do a reasonable job of optimizing when you give them a chance. For example, if you're dividing by a constant, chances are pretty good that the compiler can/will optimize that so it's done about as quickly as anything you can reasonably substitute for it.

在,但是,你有没有提前知道两个值,你需要通过其他分之一,得到的答案。如果有编译器做很多用它做的方式,它会 - 为此事,如果有很大的空间编译器优化得多吧,CPU会做这样的编译器没得。

When, however, you have two values that weren't known ahead of time, and you need to divide one by the other to get the answer. If there was much way for the compiler to do much with it, it would -- and for that matter, if there was much room for the compiler to optimize it much, the CPU would do it so the compiler didn't have to.

编辑:类似的东西你最好的选择(这是相当现实的)可能会是这样的:

Your best bet for something like that (that's reasonably realistic) would probably be something like:

double scale_factor = get_input();

for (i=0; i<values.size(); i++)
    values[i] /= scale_factor;

这是比较容易转换为是这样的:

This is relatively easy to convert to something like:

scale_factor = 1.0 / scale_factor;

for (i=0; i<values.size(); i++)
    values[i] *= scale_factor;



我真的不能保证多少的一种方式或其他有关特定的编译器这样做。它基本上是强度降低和环吊装的组合 - 有一定知道如何做到既优化,但我见过的C#编译器表明,它可能不是(但我从来没有测试任何东西完全一样,和测试我所做的就是几个版本回来...)

I can't really guarantee much one way or the other about a particular compiler doing that. It's basically a combination of strength reduction and loop hoisting -- there are certainly optimizers that know how to do both, but what I've seen of the C# compiler suggests that it may not (but I never tested anything exactly like this, and the testing I did was a few versions back...)

这篇关于C#/ XNA - 乘法比司更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆