gpt4 book ai didi

C++ 性能下降(或必须改进代码?)

转载 作者:行者123 更新时间:2023-12-03 11:09:59 25 4
gpt4 key购买 nike

我正在开发一个简单的程序,它在循环中将相同的字符串复制到另一个字符串中。我使用的是Visual Studio C++ 2019 Community Edition,项目类型为“命令行”。
如果我运行它 3,42 秒,那么计算出的每秒拷贝数是 130 601 397,但如果我运行它 77,97 秒,那么每秒拷贝数是 47 469 296 ...
程序运行的时间越长,性能下降越多......
这是代码:

#include <iostream>
#include <cstdlib>
#include <signal.h>
#include <chrono>
#include <string>

using namespace std;

unsigned long repeats_counter = 0;

std::chrono::steady_clock::time_point t1;
std::chrono::steady_clock::time_point t2;

// When CTRL+C (SIGINT), this is executed
signal_callback_handler(int signum) {
t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::cout << "Total execution time " << diff.count() << " s\n";
unsigned long average_repeats_per_sec = (unsigned long)(repeats_counter / diff.count());
std::cout << "Number of average repeats per second was " <<
std::to_string(average_repeats_per_sec) << "\n";
std::cout << "Number of average repeats per minute was " <<
std::to_string(average_repeats_per_sec * 60) << "\n";
cout << "Number of effective repeats = " << repeats_counter << endl;
// Terminate program
exit(signum);
}


int main()
{
signal(SIGINT, signal_callback_handler);
signal(SIGTERM, signal_callback_handler);

std::string from_str, to_str;

cout << "Start copying. CTRL+C to stop." << endl;
t1 = std::chrono::high_resolution_clock::now();
from_str = "the string to be copied";
while (true) {
to_str = from_str;
repeats_counter++;
}
return 0;
}

最佳答案

这可能是由整数溢出引起的。 unsigned long至少是 32 位,在某些平台上它等于 unsigned int. unsigned long long部分缓解了这个问题,但从技术上讲,循环应该有某种防御措施,尽管它增加了循环的成本。
代码可移植性有两个问题,编译器由于实现的原因省略了:

  • std::chrono::steady_clock::time_point应该是 std::chrono::high_resolution_clock::time_point
  • signal_callback_handler应该有返回类型 void
  • 关于C++ 性能下降(或必须改进代码?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65627751/

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