byte、short、int 和 long 的乘法速度是相同的还是呈对数、线性、指数增长? 我写了一个小程序来测试它。结果全部返回0;
#include <unistd.h>
#include <chrono>
#include <iostream>
using namespace std;
using namespace std::chrono;
int main()
{
short a = 0xffea, b = 0xffaa;
int result, ia = 0xffeaffae, ib = 0xeaffaeff;
long iresult, la = 0xffeaffaeffdaffad, lb = 0xeaffaeffdaffadff;
long long lresult;
auto start = high_resolution_clock::now();
result = a * b;
auto end = high_resolution_clock::now();
auto dur = duration_cast<microseconds>(end - start);
cout << "short multiplication : " << dur.count() << endl;
start = high_resolution_clock::now();
iresult = ia * ib;
end = high_resolution_clock::now();
dur = duration_cast<microseconds>(end - start);
cout << "int multiplication : " << dur.count() << endl;
start = high_resolution_clock::now();
lresult = la * lb;
end = high_resolution_clock::now();
dur = duration_cast<microseconds>(end - start);
cout << "long multiplication : " << dur.count() << endl;
return 0;
}
我假设 64 位处理器可以以相同的速度计算基本类型;
谢谢
最佳答案
它取决于机器。对于 native 数据类型,乘法指令消耗的周期数是相关的。要明确说明使用的指令,请使用内联汇编或检查汇编输出。对于英特尔处理器,this document列出许多指令的 CPU 周期。
rtdsc instruction ,除此之外,例如 cpuid 可能会让您大致了解您的部分代码使用了多少个 cpu 周期,但您可能更适合研究汇编或分析您的应用程序。
但大多数时候,这些都与练习无关。它们大约需要一个周期,大约是 0,000000001 秒。
在大多数情况下,您可以坚持您的假设并认为乘法对所有 native 数据类型具有相同的成本。
关于c++ - 不同原始类型的乘法速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52106358/