c# - Math.Floor 或 Math.Truncate 与 (int) 在正数性能方面

标签 c# .net performance math type-conversion

对于这种情况,我的假设是否正确:

double d = 3.76212; // d >= 0 && d <= Int32.MaxValue

一个人应该总是使用这个:

double truncated = (double)(int)d;

而不是这些:

double truncated = Math.Truncate(d); // 4 times slower than (double)(int) on x86, 7 times slower than (double)(int) on x64
double truncated = Math.Floor(d); // 3 times slower than (double)(int) on both x86 and x64

换句话说,只有在处理足够大的数字(x86 上 >Int32.MaxValue 和 x64 上 > Int64.MaxValue)或处理小于 0 的数字时才会使用 Math.Floor,因为 Floor 与负数的行为不同?至于 Truncate,它的使用确实应该受到限制(缺少不能放入 Int32 或 Int64 中的非常大的负数),因为它在所有情况下都比 Floor 慢?

最佳答案

我认为我们不能假设在 Framework 的 future 版本或 CLR 的 future 版本中会一直如此。

您可以做的是创建一个您调用的简单辅助类,然后将实现细节隐藏在该类中。然后,当出现新的 CLR/Framework 时,您可以重新进行测量并根据需要更新帮助程序类:

double truncated = FastMath.Truncate(d);

并按照

public static double Truncate(double d)
{
    if ((d >= Int32.MinValue) && (d <= Int32.MaxValue))
    {
        ...
    }
}

关于c# - Math.Floor 或 Math.Truncate 与 (int) 在正数性能方面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25424880/

相关文章:

c# - 如何在 C# 中启动 'Scheduled Task Wizard'?

c# - 在 DataGridView 中以编程方式选择行

c# - Func<T>.BeginInvoke 是否使用线程池?

mysql - 2 列索引与 3 列索引性能方面

performance - Go 中 CSV 和 map 的性能不佳

c# - 我如何使用 SendGridAPIClient 发送电子邮件。 Azure 网站

c# - 如何让线程休眠直到收到异步函数的回调?

c# - C#/WinRT 中的全局状态对象

c# - 为什么我有时有一个 app.config 而有时有一个 binaryname.dll.config 文件?

AngularJS ng-repeat 对于大量数据来说非常慢