相关疑难解决方法(0)

轻松测量经过的时间

我正在尝试使用time()来衡量我的程序的各个点.

我不明白为什么之前和之后的值是一样的?我知道这不是描述我的程序的最佳方式,我只想看看有多长时间.

printf("**MyProgram::before time= %ld\n", time(NULL));

doSomthing();
doSomthingLong();

printf("**MyProgram::after time= %ld\n", time(NULL));
Run Code Online (Sandbox Code Playgroud)

我试过了:

struct timeval diff, startTV, endTV;

gettimeofday(&startTV, NULL); 

doSomething();
doSomethingLong();

gettimeofday(&endTV, NULL); 

timersub(&endTV, &startTV, &diff);

printf("**time taken = %ld %ld\n", diff.tv_sec, diff.tv_usec);
Run Code Online (Sandbox Code Playgroud)

我如何阅读结果**time taken = 0 26339?这是否意味着26,339纳秒= 26.3毫秒?

那怎么说**time taken = 4 45025,这意味着4秒和25毫秒?

c c++ linux time measurement

272
推荐指数
12
解决办法
48万
查看次数

处理C++泛型编程中的void赋值

我有C++代码包装任意lambda并返回lambda的结果.

template <typename F>
auto wrapAndRun(F fn) -> decltype(F()) {
    // foo();
    auto result = fn();
    // bar();
    return result;
}
Run Code Online (Sandbox Code Playgroud)

这有效,除非Freturn void(error: variable has incomplete type 'void').我想用a ScopeGuard来运行bar,但我不想bar在fn投掷时运行.有任何想法吗?

c++

31
推荐指数
4
解决办法
1932
查看次数

使用 -O3 或 -Ofast 来编译您的基准代码是否现实,还是会删除代码?

当使用下面的基准代码编译时,-O3它在延迟方面的差异给我留下了深刻的印象,所以我开始怀疑编译器是否通过以某种方式删除代码而“作弊”。有没有办法检查?我可以安全地进行基准测试-O3吗?期望速度提高 15 倍是否现实?

没有的结果-O3:平均:239纳米最小:230 纳米(900 万次迭代) 有
结果-O3:平均:14纳米,最小:12 纳米(900 万次迭代)

int iterations = stoi(argv[1]);
int load = stoi(argv[2]);

long long x = 0;

for(int i = 0; i < iterations; i++) {

    long start = get_nano_ts(); // START clock

    for(int j = 0; j < load; j++) {
        if (i % 4 == 0) {
            x += (i % 4) * (i % 8);
        } else {
            x …
Run Code Online (Sandbox Code Playgroud)

c++ optimization g++ compiler-flags compiler-optimization

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