c++ - 为什么基准测试 mod 运算符 (%) 经常显示 0 时间,即使是 5,000 轮?
问题描述
我想了解模数 ( %
) 运算符的运行速度。我已经设置了一个简单的程序来%
对随机生成的值进行基准测试。使用高分辨率时钟以纳秒为单位测量时间。它经常报告 0ns 已经过去。显然什么都不会立即发生,那为什么会这样呢?如果我将轮数增加到大约 50,000 次,通常需要大约 1,000,000ns。但即使是 5000 轮也总是 0ns 。我是不是测量错了?正在做哪些优化来实现这一点?
#include <iostream>
#include <chrono>
#include <random>
void runTest(const int rounds, const int min, const int max);
int main()
{
std::cout << "started" << std::endl;
runTest(5000, 1000000, 2000000);
return 0;
}
/*IN: number of rounds to run on the test, the min and max value to choose between for operands to mod
OUT: time taken (in nanoseconds) to complete each operation on the same randomly generated numbers*/
void runTest(const int rounds, const int min, const int max)
{
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(min,max); // guaranteed unbiased
std::chrono::nanoseconds durationNormalMod = std::chrono::nanoseconds::zero();
std::chrono::nanoseconds durationFastMod = std::chrono::nanoseconds::zero();
long long result = 0;
for(auto i = 0; i < rounds; i++)
{
const int leftOperand = uni(rng);
const int rightOperand = uni(rng);
auto t1 = std::chrono::high_resolution_clock::now();
long long x = (leftOperand % rightOperand);
auto t2 = std::chrono::high_resolution_clock::now();
//std::cout << "x: " << x << std::endl;
result += x;
durationNormalMod += std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1);
}
std::cout << "duration of %: " << durationNormalMod.count() << std::endl;
std::cout << "result: " << result << std::endl;//preventing optimization by using result
}
我用g++ prog.cpp -o prog.exe -O3
.
我很感兴趣,因为我有一个特定的案例,我可以使用不同的算法来实现模数,我很好奇它是否更快。
解决方案
在进行基准测试时,重要的是:
以某种方式使用计算结果。任何从未使用过的结果以及导致它的计算都可以并且将被优化编译器删除。
时间不是单个计算,而是许多计算,因此时钟访问之间经过的时间大约为毫秒。这是因为时钟访问是一项相对昂贵的操作,并且会显着扭曲非常快速计算的时序。
禁用 CPU 时钟频率缩放或至少在测量时间之前预热 CPU。
推荐阅读
- security - 保护 .NET Core MVC 网站免受暴力登录尝试(通过内置方式)
- html - 我的标题在按钮悬停效果时晃动
- javascript - JavaScript 动态同步函数队列
- sql-server - 在 If 语句中使用值后从存储过程中返回一个值
- r - 文件中出现错误(文件,“rt”):无法打开连接
- monitoring - Geneos 文件系统监控 .snapshot
- javascript - 带有 Typescript TS2604 错误的动态导入 ES6 React 组件?
- entity - 是否可以在 Visio 中使用类似 XL 表的结构创建 ERD?我需要在每个属性旁边显示列(单选框)
- php - 来自 MySQL 数据库的数据显示在文本字段中,但不通过 php 显示在文本区域中
- c++ - 浮点异常(核心转储)#694457