c++ MSYS2的g++编译器上的std::clock()是否损坏?

huus2vyu  于 2023-02-10  发布在  其他
关注(0)|答案(1)|浏览(149)

我正在尝试编写一个简单的单头基准测试程序,我知道std::clock会给予我一个进程(线程)实际使用的时间。
因此,给定以下简化程序:

nt main() {
    using namespace std::literals::chrono_literals;
    auto start_cpu = std::clock();
    auto start_wall = std::chrono::high_resolution_clock::now();
    // clobber();
    std::this_thread::sleep_for(1s);
    // clobber();
    auto finish_cpu = std::clock();
    auto finish_wall = std::chrono::high_resolution_clock::now();
    std::cerr << "cpu: "
        << start_cpu << " " << finish_cpu << " "
        << (finish_cpu - start_cpu) / (double)CLOCKS_PER_SEC << " s" << std::endl;
    std::cerr << "wall: "
        // << FormatTime(start_wall) << " " << FormatTime(finish_wall) << " "
        << (finish_wall - start_wall) / 1.0s << " s" << std::endl;
    return 0;
}

Demo
我们得到以下输出:

cpu: 4820 4839 1.9e-05 s
wall: 1.00007 s

我只想澄清一下cpu时间是它执行代码的时间,而这些代码实际上并不是sleep_for代码,因为这实际上是由内核完成的,而std::clock并不跟踪这些代码。

int main() {
    using namespace std::literals::chrono_literals;
    int value = 0;
    auto start_cpu = std::clock();
    auto start_wall = std::chrono::high_resolution_clock::now();
    // clobber();
    for (int i = 0; i < 1000000; ++i) {
        srand(value);
        value = rand();
    }
    // clobber();
    std::cout << "value = " << value << std::endl;
    auto finish_cpu = std::clock();
    auto finish_wall = std::chrono::high_resolution_clock::now();
    std::cerr << "cpu: "
        << start_cpu << " " << finish_cpu << " "
        << (finish_cpu - start_cpu) / (double)CLOCKS_PER_SEC << " s" << std::endl;
    std::cerr << "wall: "
        // << FormatTime(start_wall) << " " << FormatTime(finish_wall) << " "
        << (finish_wall - start_wall) / 1.0s << " s" << std::endl;
    return 0;
}

Demo这给了我一个输出:

cpu: 4949 1398224 1.39328 s
wall: 2.39141 s
value = 354531795

到目前为止,一切顺利。然后我在运行MSYS2的g++编译器的Windows机器上尝试了这个方法。最后一个程序的输出给了我:

value = 0
cpu: 15 15 0 s
wall: 0.0080039 s

std::clock()始终输出15?std::clock()的编译器实现是否已损坏?

z9smfwbn

z9smfwbn1#

看起来我假设CLOCKS_PER_SEC会是一样的。但是,在mSYS2编译器上,它比godbolt.org上少了1000倍。

相关问题