如何解决c编程中标准math.h库的pow和powf执行时间不同
我目前正在用 C 代码对几种算法进行基准测试。我发现了以下无法解释的行为:
在比较 math.h 库的 pow()
和 powf()
函数的执行时间时,执行 powf()
函数比 pow()
慢两倍。>
我只使用 powf()
的 float 值和 pow() 的 double 值,所以不应该有任何隐式类型转换。
我在 beaglebone black 上执行代码并使用 gcc 编译它。目前,我不使用任何优化标志。如果使用 -O3
,则执行时间几乎相同。
有没有解释为什么 powf()
慢这么多?
这是我所做的最小示例:
#include<time.h>
#include <stdio.h>
#include <math.h>
struct timespec diff_time(struct timespec start,struct timespec end)
{
struct timespec temp;
if ((end.tv_nsec - start.tv_nsec) < 0) {
temp.tv_sec = end.tv_sec - start.tv_sec - 1;
temp.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
}
else {
temp.tv_sec = end.tv_sec - start.tv_sec;
temp.tv_nsec = end.tv_nsec - start.tv_nsec;
}
return temp;
}
int main() {
struct timespec time1,time2;
double time_diff;
double result=0;
float resultf=0;
double value = 234.2348;
float valuef = 234.2348f;
int j;
int select_switch = 1;
//TIC
clock_gettime(CLOCK_REALTIME,&time1);
if (select_switch == 1) {
for (j = 0; j < 1000; j++)
{
result = pow(value,2);
}
}
if (select_switch == 2) {
for (j = 0; j < 1000; j++)
{
resultf = powf(valuef,2.0f);
}
}
if (select_switch == 4) {
for (j = 0; j < 1000; j++)
{
resultf = valuef * valuef;
}
}
if (select_switch == 5) {
for (j = 0; j < 1000; j++)
{
result = value * value;
}
}
/* TOC */
clock_gettime(CLOCK_REALTIME,&time2);
time_diff = diff_time(time1,time2).tv_sec * (1e3) +
(diff_time(time1,time2).tv_nsec) * (1e-6); // in Milli Seconds
printf("%lf",result);
printf("%f",resultf);
}
解决方法
只是在黑暗中拍摄:
如果硬件只实现了double,那么float会比较慢,如果 作为本机双格式的转换不是免费的 浮动加载和浮动存储指令。
供参考:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。