C++ Clock Not Working [closed]

孤街浪徒 提交于 2019-12-04 22:06:59

In the standard, clock() is specified to return the approximate processor time used by the process. In particular that means that the duration resulting from an expression (finish-start) doesn't necessarily equal the amount of wall-clock time that has passed. For example if you measure four threads chewing up CPU for 1 second then you should get a result of about 4 seconds.

The way this is relevant to your program is that a program that is just waiting for input or sleeping is not using any processor time, so the result of (finish-start) will be zero.

#include <iostream>

#include <chrono>   // std::chrono::seconds, milliseconds
#include <thread>   // std::this_thread::sleep_for

#include <ctime>    // std::clock()

int main() {
    auto start_processor_usage = std::clock();
    auto start_wall_clock = std::chrono::steady_clock::now();

    std::this_thread::sleep_for(std::chrono::seconds(1));

    auto finish_processor_usage = std::clock();
    auto finish_wall_clock = std::chrono::steady_clock::now();

    std::cout << "CPU usage: " << (finish_processor_usage - start_processor_usage) / CLOCKS_PER_SEC << '\n';
    std::cout << "Wall clock: " << (finish_wall_clock - start_wall_clock) / std::chrono::milliseconds(1) << '\n';
}

The above program should output something like:

CPU usage: 0
Wall clock: 1000

Note that while *nix platforms in general correctly implement clock() to return processor usage, Windows does not. On Windows clock() returns wall-clock time. You need to keep this in mind when switching between Windows and other platforms.


Ok Sure. What is the syntax for a random int using <random>? – Noguiguy

#include <random>

int main() {
  // initialize with random seed
  std::random_device r;
  std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
  std::mt19937 engine(seed);

  // define distribution: improved version of "% 4 + 1"
  auto one_to_four = std::uniform_int_distribution<>(1, 4);

  // generate number
  auto actualNumber = one_to_four(engine);
}

I also find clock() does not give the result I want. So I just wrote a simple Timer class to do the time duration calculation using QueryPerformanceCounter on Windows and clock_gettime on Linux

Just try this: https://github.com/AndsonYe/Timer

:)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!