在C#中的数学优化 [英] Math optimization in C#

查看:151
本文介绍了在C#中的数学优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经整天在分析应用程序,并经优化code的一对夫妇的位,我离开了这个我的待办事项清单上。它是一个神经网络,被调用超过100万次的激活功能。根据dotTrace,它相当于整体功能的时间约60%。

你会如何优化呢?

 公共静态浮动乙状结肠​​(double值){
    回报(浮)(1.0 /(1.0 + Math.Pow(Math.E,-value)));
}


解决方案

尝试:

 公共静态浮动乙状结肠​​(double值){
    返回1.0F /(1.0F +(浮点)Math.Exp( - 值));
}

编辑:我做了快速基准。在我的机器,上面code是比你的方法快43%左右,这在数学上等价code是teeniest有点快(比原来快46%):

 公共静态浮动乙状结肠​​(double值){
    浮K = Math.Exp(值);
    返回K /(1.0F + K);
}

编辑2:我不知道开销C#功能有多少,但如果你的#include<文件math.h> 中源$ C ​​$ C,你应该能够利用这一点,它采用了浮动EXP函数。这可能是一个快一点。

 公共静态浮动乙状结肠​​(double值){
    浮K = expf((浮点)值);
    返回K /(1.0F + K);
}

此外,如果你正在做的数以百万计的电话,该函数调用的开销可能是一个问题。试着做一个内联函数,看看如果这是任何帮助。

I've been profiling an application all day long and, having optimized a couple bits of code, I'm left with this on my todo list. It's the activation function for a neural network, which gets called over a 100 million times. According to dotTrace, it amounts to about 60% of the overall function time.

How would you optimize this?

public static float Sigmoid(double value) {
    return (float) (1.0 / (1.0 + Math.Pow(Math.E, -value)));
}

解决方案

Try:

public static float Sigmoid(double value) {
    return 1.0f / (1.0f + (float) Math.Exp(-value));
}

EDIT: I did a quick benchmark. On my machine, the above code is about 43% faster than your method, and this mathematically-equivalent code is the teeniest bit faster (46% faster than the original):

public static float Sigmoid(double value) {
    float k = Math.Exp(value);
    return k / (1.0f + k);
}

EDIT 2: I'm not sure how much overhead C# functions have, but if you #include <math.h> in your source code, you should be able to use this, which uses a float-exp function. It might be a little faster.

public static float Sigmoid(double value) {
    float k = expf((float) value);
    return k / (1.0f + k);
}

Also if you're doing millions of calls, the function-calling overhead might be a problem. Try making an inline function and see if that's any help.

这篇关于在C#中的数学优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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