相关疑难解决方法(0)

每个程序员应该了解的内存?

我想知道Ulrich Drepper 从2007年开始对每个程序员应该知道的内容有多少仍然有效.另外,我找不到比1.0更新的版本或勘误表.

optimization x86 memory-management cpu-architecture micro-optimization

145
推荐指数
3
解决办法
2万
查看次数

29
推荐指数
3
解决办法
2万
查看次数

是否可以使用std :: atomic与POD结构,除了它有一个construtor?

我正在使用一些原子变量,所有unsigned int,我想将它们收集到一个结构中 - 实际上是一个POD.但是我也想要一个构造函数,因为我的编译器不是c ++ 11(所以我必须定义自己的构造函数来创建初始值).

所以最初我有:

// Names are not the real names - this is just for example
std::atomic<int> counter1;
std::atomic<int> counter2;
std::atomic<int> counter3;
Run Code Online (Sandbox Code Playgroud)

然后我很乐意根据需要增加/减少它们.但后来我决定再多一些计数器,因此将它们放入一个结构中:

struct my_counters {
    int counter1;
    int counter2;
    int counter3;
    // Constructor so that I can init the values I want.
    my_counters(c1, c2, c3) : counter1(c1), counter2(c2), counter3(c3){;}
};
Run Code Online (Sandbox Code Playgroud)

但是因为我添加了一个自定义构造函数,所以这在技术上不再是POD.我正在阅读有关此问题的其他问题,他们说使用std :: atomic我需要一个POD,但我读到的其他问题表明结构需要是可复制的或者一些这样的...无论如何,我感到很困惑,我想要要知道我是否可以安全地使用我的结构my_counters作为原子类型:

std::atomic<my_counters> counters;
Run Code Online (Sandbox Code Playgroud)

然后在各种线程内:

// Are these operations now still atomic (and therefore safe to use across threads):
counters.counter1++;
counters.counter2--;
counters.counter3 …
Run Code Online (Sandbox Code Playgroud)

c++ struct stdatomic

3
推荐指数
2
解决办法
1030
查看次数

为什么对已排序数组求和比对未排序数组求和更快?

我有一个ArrayList,其中的数字从 10 MM 到 20 MM

 List<Long> l = new ArrayList<>();
        for (long i = 10_000_000; i < 20_000_000; i++) {
            l.add(i);
        }
Run Code Online (Sandbox Code Playgroud)

为什么sum()函数在排序数组上比在未排序数组上更快?

public class Main {

    public static void main(String[] args) {
        List<Long> l = new ArrayList<>();
        for (long i = 10_000_000; i < 20_000_000; i++) {
            l.add(i);
        }

        System.out.println(sum(l));

        Collections.shuffle(l);
        System.out.println(sum(l));

        Collections.sort(l);
        System.out.println(sum(l));
    }

    static long sum(List<Long> l) {
        long started = System.nanoTime();
        long result = 0;
        for (long v : l) { …
Run Code Online (Sandbox Code Playgroud)

java arrays sorting cpu benchmarking

1
推荐指数
1
解决办法
316
查看次数