相关疑难解决方法(0)

基准测试,代码重新排序,易失性

我决定要对特定函数进行基准测试,所以我天真地编写如下代码:

#include <ctime>
#include <iostream>

int SlowCalculation(int input) { ... }

int main() {
    std::cout << "Benchmark running..." << std::endl;
    std::clock_t start = std::clock();
    int answer = SlowCalculation(42);
    std::clock_t stop = std::clock();
    double delta = (stop - start) * 1.0 / CLOCKS_PER_SEC;
    std::cout << "Benchmark took " << delta << " seconds, and the answer was "
              << answer << '.' << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

一位同事指出,我应该声明startstop变量volatile以避免代码重新排序.他建议优化器可以,例如,有效地重新排序代码,如下所示:

    std::clock_t start = std::clock();
    std::clock_t stop = …
Run Code Online (Sandbox Code Playgroud)

c++ benchmarking volatile compiler-optimization

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

函数调用的序列点?

这是另一个序列点问题,但是一个相当简单的问题:

#include <stdio.h>
void f(int p, int) {
  printf("p: %d\n", p);
}

int g(int* p) {
  *p = 42;
  return 0;
}

int main() {
  int p = 0;
  f(p, g(&p));
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是未定义的行为吗?或者调用g(&p)充当序列点?

c c++ undefined-behavior sequence-points

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