我正在尝试实现一个计时器类,它打印给定范围所需的时间。不知怎的,我无法让它正常工作。到目前为止我的代码:
Main.cpp:
#include "scopetimer.hpp"
#include <cstdlib>
#include <cmath>
#include <string>
#include <chrono>
#include <iostream>
void work01()
{
double numbers[10000];
for (int i = 0; i < 10000; ++i)
{
numbers[i] = double(std::rand()) / double(RAND_MAX);
}
for (int n = 10000; n > 1; n = n - 1) {
for (int i = 0; i < n - 1; i = i + 1) {
if (numbers[i] > numbers[i + 1]) {
double tmp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = tmp;
}
}
}
}
void work02()
{
int* buf[1024];
for (int i = 2; i < 1024; ++i)
buf[i] = new int[i];
for (int i = 2; i < 1024; ++i)
delete[] buf[i];
}
// counts the number of primes in an interval
int work03(int n0, int n1)
{
int freq = n1 - n0 + 1;
for (int i = n0; i <= n1; ++i)
{
// Have fun: use the alternative iteration direction and see how fast
// it gets!
// for(int j = 2; j < i; ++j)
for (int j = i - 1; j > 1; --j)
{
if (i%j == 0)
{
--freq;
break;
}
}
}
return freq;
}
int main(int, char**)
{
{ ScopeTimer("work01");
work01();
}
{
ScopeTimer("work02");
work02();
}
{
ScopeTimer("work03");
work03(0, 10000);
}
std::cout << std::endl << "Tests" << std::endl << std::endl;
{
clock_t start_(std::clock());
work01();
clock_t end_(std::clock());
std::cout << "Test Timer: " << end_ - start_ << "ns" << std::endl;
}
{
clock_t start_(std::clock());
work02();
clock_t end_(std::clock());
std::cout << "Test Timer: " << end_ - start_ << "ns" << std::endl;
}
{
clock_t start_(std::clock());
work03(0,10000);
clock_t end_(std::clock());
std::cout << "Test Timer: " << end_ - start_ << "ns" << std::endl;
}
system("Pause");
}
scopetimer.cpp
#include "scopetimer.hpp"
#include <cmath>
#include <string>
#include <chrono>
#include <iostream>
ScopeTimer::ScopeTimer(const std::string& name)
:name_(name),
start_(std::clock()) {
}
ScopeTimer::~ScopeTimer() {
double elapsed = (double(std::clock() - start_) / double(CLOCKS_PER_SEC));
std::cout << name_ << ": " << int(elapsed) << "ns" << std::endl;
}
我测试了ScopeTimer()之外的时钟函数,它工作正常。因此,据我所知,唯一的问题是我无法使ScopeTimer()工作。它总是打印0ns。我主要关注的是:https://felix.abecassis.me/2011/09/cpp-timer-raii/
亲切的问候
答案 0 :(得分:0)
在~ScopeTimer()
中,您打印已经过了多少完整秒数而不是多少纳秒,而在main
的第二部分中,您打印的时钟滴答数可能相同也可能不同作为一个纳秒。
答案 1 :(得分:0)
我遇到了同样的问题
对我来说,解决方案是定义ScopeTimer实例,而不是仅调用其构造函数,我的意思是:
{
ScopeTimer _scopetimer("work01");
work01();
}
应该可以
我猜编译器似乎忽略(优化)了,因为当您仅调用ScopeTimer(“ work01”)时。