【发布时间】:2018-05-13 09:00:23
【问题描述】:
下面是一些代码,用于根据输入获取下一个素数。我也在测量完成操作需要多长时间(以纳秒为单位)。
我在 Visual Studio 2017(社区版)中使用 C++。我输入的一些数字的结果从小数字(1-100)的 300 纳秒到 800 纳秒(1,000,000,000 和更高)。但是,如果我输入 65535,我会得到 97767 纳秒。但是当我输入 65533 时,它是 438 纳秒,当我输入 65539 时,它是 487 纳秒。
我的问题是:为什么 65535 需要更长的时间来计算,但对于高于或低于它的其他数字,它明显更低?
#include "stdafx.h"
#include <string>
#include <iostream>
#include <chrono>
bool isPrime(int num)
{
int divisor = 3;
while (divisor != INT_MAX)
{
if (divisor % 2 == 0)
{
divisor++;
}
if (num % divisor == 0)
{
return true;
}
divisor += 2;
}
return false;
}
int findNextPrime(int num)
{
while (num != INT_MAX)
{
if (num % 2 == 0)
{
num++;
}
else
{
num += 2;
}
if (isPrime(num))
{
return num;
}
else
{
num++;
}
}
return -1;
}
int main()
{
int candidatePrime;
std::string str;
std::cin >> candidatePrime;
const auto start = std::chrono::high_resolution_clock::now();
const int nextPrime = findNextPrime(candidatePrime);
const auto end = std::chrono::high_resolution_clock::now();
std::cout << nextPrime << std::endl;
std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()
<< " nanoseconds" << std::endl;
std::cin >> str;
return 0;
}
【问题讨论】:
-
首先,确保您正在计时优化构建。其次,使用分析器查看时间花费在何处以及如何花费。
标签: c++ performance