我改变了this code并编写了这个函数:
#include <ctime>
#include <iomanip>
#include <iostream>
#include <chrono>
#define TIMER(name) Timer timer__(name);
class Timer
{
public:
Timer(const std::string& name) :
name_(name), start_(std::chrono::system_clock::now())
{
}
~Timer()
{
auto duration = std::chrono::system_clock::now() - start_;
std::cout << std::setw(90) << std::left << name_ << ": " << std::chrono::duration_cast<std::chrono::seconds>(duration).count() << "s" << std::endl;
}
private:
std::string name_ = 0;
std::chrono::time_point<std::chrono::system_clock> start_ ;
};
问题是有时我会遇到段错误。
用法:
在 main() 中放入这样的东西:
TIMER("Total time");
我用 gcc 5.2.1 编译程序。
最佳答案
有两点说明:
1. 如@Mankarse 所述,从 std::string name_ = 0;
中删除 = 0;
2. 来自here :
Each identifier that contains a double underscore __ or begins with an underscore followed by an uppercase letter is reserved to the implementation for any use.
因此,将 Timer timer__(name)
更改为 Timer my_timer(name)
关于c++ - 使用 std::chrono 计算耗时时出现“段错误”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34448747/