需要减少我的C++代码的执行时间
Need to reduce the execution time of my C++ code
所以我需要编写一个程序来总结控制台输入中的数字。数字可以嵌入字符串中(例如 hello134 或 hi -12(。这是运行良好但超过时间限制(>1s(的代码。
那么,如何减少执行时间呢?这是我的程序未能通过的测试:https://pastebin.com/HNL9Vz7E
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string line;
long p = 0;
int i = 0;
int b, e;
long long sum = 0;
while (getline(cin, line))
{
for (int i = 0; i < line.size(); i++)
{
if (isdigit(line[i]) || line[i] == '-' && isdigit(line[i + 1]))
{
b = i;
while (isdigit(line[++i]))
{}
e = i;
p = stoi(line.substr(b, b - e));
sum += p;
}
}
}
cout << sum << endl;
return 0;
}
可能是
line.substr(b, b - e)
我认为应该是
line.substr(b, e - b)
相反。它总是复制这一行中的大字符串。 使用该示例文件需要不到一毫秒的时间,但与未更改代码的一秒也相去甚远。而且:正则表达式比按自己的方式做要慢得多。
相关文章:
- 需要减少我的C++代码的执行时间
- 视觉在C 中获取每行代码的执行时间
- 测量执行时间 - 在程序代码或外壳中
- 第一次在 Linux 上执行 c++ 代码的时间非常慢
- 最佳C 11测量嵌入式系统代码执行时间的方法
- 两个代码段之间执行时间的奇怪差异
- 预先设置c++代码的执行时间
- 为什么要在我的OpenMP代码中增加执行时间
- 如何减少以下代码的执行时间
- 执行代码的时间百分比为x
- 2个代码的执行时间的数目将不同
- 在 OpenMP 代码C++测量执行时间
- 如何减少以下代码的C++执行时间
- 当我从Java代码执行C++程序时,我应该如何测量它的执行时间
- C++和Haskell代码在不同机器上的执行时间不同
- 有什么方法可以减少这个代码的执行时间吗
- 英特尔TBB代码有不同的执行时间在windows和linux
- 如何获得一个c++代码段执行时间的客观评价
- 如何在c++中获得一段代码的执行时间
- Linux中的代码执行时间