【问题标题】:Performance when reaching 65535 jumps wildly compared to other input与其他输入相比,达到 65535 时的性能大幅提升
【发布时间】: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


【解决方案1】:

首先,您的bool isPrime(int num) 不检查数字是否为质数。以 25 为例。你应该首先尝试解决这个问题。也看看这里Determining if a number is prime

但要回答您的问题: 当您输入 65533 时,您调用 is_prime 并使用 65535 可被 3 整除,因此您的 while (divisor != INT_MAX) 循环将只运行 1 次。

当您输入 65535 时,您使用 65537 调用 is_prime,这是一个质数,因此您的 while (divisor != INT_MAX) 循环将运行约 32767 次。

对于素数,您的函数需要更长的时间才能运行,这很正常。

【讨论】:

    猜你喜欢
    • 2015-10-17
    • 2011-04-16
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    相关资源
    最近更新 更多