相关疑难解决方法(0)

为什么处理排序数组比处理未排序数组更快?

这是一段看似非常特殊的C++代码.出于某种奇怪的原因,奇迹般地对数据进行排序使得代码几乎快了六倍.

#include <algorithm>
#include <ctime>
#include <iostream>

int main()
{
    // Generate data
    const unsigned arraySize = 32768;
    int data[arraySize];

    for (unsigned c = 0; c < arraySize; ++c)
        data[c] = std::rand() % 256;

    // !!! With this, the next loop runs faster.
    std::sort(data, data + arraySize);

    // Test
    clock_t start = clock();
    long long sum = 0;

    for (unsigned i = 0; i < 100000; ++i)
    {
        // Primary loop
        for (unsigned c = 0; c < arraySize; ++c) …
Run Code Online (Sandbox Code Playgroud)

c++ java optimization performance branch-prediction

2万
推荐指数
27
解决办法
142万
查看次数

逐行访问矩阵元素与列方式

A[i][j]给出了一个矩阵.如果我们想添加矩阵的元素,哪种方法更好,为什么?

  1. 列明智
  2. 划明

从我的观点来看,行方式更好,因为在数组表示元素存储在连续的内存位置,因此访问它们花费的时间更少.但是因为在RAM中获取每个位置需要相同的时间,这是否重要?

c arrays

11
推荐指数
1
解决办法
2万
查看次数

标签 统计

arrays ×1

branch-prediction ×1

c ×1

c++ ×1

java ×1

optimization ×1

performance ×1