gpt4 book ai didi

c++ - trunc 函数是否很慢?

转载 作者:太空宇宙 更新时间:2023-11-03 10:42:54 25 4
gpt4 key购买 nike

tl;dr: double b=a-(size_t)(a)double b=a-trunc(a)

我正在为图像实现旋转功能,我注意到 trunc 功能似乎非常慢。

图像的循环代码,像素的实际影响在性能测试中被注释掉了,所以我什至不访问像素。

double sina(sin(angle)), cosa(cos(angle));
int h = (int) (_in->h*cosa + _in->w*sina);
int w = (int) (_in->w*cosa + _in->h*sina);
int offsetx = (int)(_in->h*sina);

SDL_Surface* out = SDL_CreateARGBSurface(w, h); //wrapper over SDL_CreateRGBSurface

SDL_FillRect(out, NULL, 0x0);//transparent black
for (int y = 0; y < _in->h; y++)
for (int x = 0; x < _in->w; x++){
//calculate the new position
const double destY = y*cosa + x*sina;
const double destX = x*cosa - y*sina + offsetx;

所以这里是使用trunc

的代码
size_t tDestX = (size_t) trunc(destX);
size_t tDestY = (size_t) trunc(destY);
double left = destX - trunc(destX);
double top = destY - trunc(destY);

这是更快的等价物

size_t tDestX = (size_t)(destX);
size_t tDestY = (size_t)(destY);
double left = destX - tDestX;
double top = destY - tDestY;

答案建议在转换回整数时不要使用 trunc 所以我也尝试了这种情况:

size_t tDestX = (size_t) (destX);
size_t tDestY = (size_t) (destY);
double left = destX - trunc(destX);
double top = destY - trunc(destY);

快速版本似乎平均需要 30 毫秒来浏览完整图像 (2048x1200),而使用 trunc 的慢速版本对于同一图像大约需要 135 毫秒。只有两次调用 trunc 的版本仍然比没有调用的版本慢很多(大约 100 毫秒)。

据我了解 C++ 规则,两个表达式应该始终返回相同的内容。我在这里错过了什么吗? dextXdestY 被声明为 const 因此只应调用一次 trunc 函数,即使这样它也不会' 自己解释慢三倍以上的因素。

我正在使用优化 (/O2) 的 Visual Studio 2013 进行编译。是否有任何理由使用 trunc 函数?即使使用整数获取小数部分似乎也更快。

最佳答案

按照您的使用方式,您没有理由使用 trunc function根本。它将 double 转换为 double ,然后将其转换为积分并丢弃。替代方案更快这一事实并不令人惊讶。

关于c++ - trunc 函数是否很慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30588131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com