相同的代码在不同的机器上具有截然不同的运行时间

时间:2017-05-16 11:06:05

标签: c++

如果我运行此代码

#include <iostream>
#include <string>
#include <stdlib.h>
#include <vector>
#include <time.h>
#include <thread>
#include <ctime>
using namespace std;
int main()
{
    int start_s = clock();
    char randChar;
    string random;
    random.clear();
    int entry_size = 4;
    int population_size = 500000;
    vector<string> population;
    for (int i = 0; i < population_size; i++) {
        for (int i = 0; i < (unsigned)entry_size; i++) {
            randChar = rand() % 25 + 97;
            random += randChar;
        }
        //cout << random<<endl;
        population.push_back(random);
        random.clear();
    }
    int stop_s = clock();
    cout<< (stop_s - start_s)/(double)(CLOCKS_PER_SEC);
}

在此网站上:http://cpp.sh/运行时间约为0.16秒 但是,如果我在我的家用机器上编译并运行它(i5 4460 16 gb ram,机械硬盘,视觉工作室2017),运行时间约为6.6秒,大约慢了41倍,是什么造成如此巨大的速度差异?
感谢

3 个答案:

答案 0 :(得分:7)

我的精神力量表明您使用Visual Studio在家用计算机上构建了 Debug 版本。将解决方案翻转为发布版本,然后观察效果。

我刚用Visual Studio测试过。 Debug和Release之间的差异是你的代码的100倍。 (8秒vs。08秒)。

并非Debug构建本质上很慢。只是非常紧凑的循环,数学,内存或任何非阻塞可以高度优化。

答案 1 :(得分:1)

处理内存管理的机制可能不同?很难确切地指出可能有很多假设,但有两种方法可以让你的代码在两端更快。

#include <iostream>
#include <string>
#include <stdlib.h>
#include <vector>
#include <time.h>
#include <thread>
#include <ctime>
using namespace std;
int main()
{
    int start_s = clock();
    char randChar;
    string random;

无需清除空洞的东西。

    int entry_size = 4;
    int population_size = 500000;
    vector<string> population;

预先分配向量,500000是一个巨大的数字,向量必须做很多分配。

    population.resever(population_size);

另外,预先分配字符串random,并且不要在每个循环中清除它。内存量很小,但分配和取消分配是很昂贵的。而是以dinamically方式更改预分配字符串的值。

    random.reserve(entry_size);
    for (int i = 0; i < population_size; i++) {

你使用'i'作为内部和外部for循环的键,这看起来像一个错误,我正在将内循环的索引更改为j。

        for (int j = 0; j < (unsigned)entry_size; j++) {
            randChar = rand() % 25 + 97;
            random[j] = randChar;
        }
        population.push_back(random);
    }
    int stop_s = clock();
    cout<< (stop_s - start_s)/(double)(CLOCKS_PER_SEC);
}

这应该会让你的应用程序更快。

答案 2 :(得分:0)

我认为这个因素中的一些会产生影响:CPU,操作系统,内存大小,I / O速度(因为你的代码没有任何IO,所以不在你的情况下),内存缓存,并行化。