获取以毫秒为单位的时间差
Getting a time difference in milliseconds
我正在尝试做一些我认为非常简单的事情,但我到处都看了,但我无法弄清楚。我也是 C++ 的新手,对模板等没有很好的理解。
我只需要一个函数来测量从程序启动到某一点的时间(以毫秒为单位),例如:
class timeCounter {
private:
long startTime;
long currentTime;
long timeDifference;
public:
long getTime();
}
timeCounter::timeCounter () {
startTime = time.now();
}
long timeCounter::getTimePassed () {
currentTime = time.now();
timeDifference = timeNow - timeStart;
return timeDifference;
}
我试过 clock() / CLOCKS_PER_SECONDS
但结果比一秒还慢。
谁能帮帮我?
非常感谢!
我最近正在编写一个类似的系统来获取游戏引擎的增量时间。
使用 std::chrono
库,这里有一个例子:
#include <iostream>
#include <chrono>
#include <thread>
class timer
{
// alias our types for simplicity
using clock = std::chrono::system_clock;
using time_point_type = std::chrono::time_point < clock, std::chrono::milliseconds > ;
public:
// default constructor that stores the start time
timer()
{
start = std::chrono::time_point_cast<std::chrono::milliseconds>(clock::now());
}
// gets the time elapsed from construction.
long /*milliseconds*/ getTimePassed()
{
// get the new time
auto end = clock::now();
// return the difference of the times
return (end - start).count();
}
private:
time_point_type start;
};
int main()
{
timer t;
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << t.getTimePassed();
std::cin.get();
}
我正在尝试做一些我认为非常简单的事情,但我到处都看了,但我无法弄清楚。我也是 C++ 的新手,对模板等没有很好的理解。
我只需要一个函数来测量从程序启动到某一点的时间(以毫秒为单位),例如:
class timeCounter {
private:
long startTime;
long currentTime;
long timeDifference;
public:
long getTime();
}
timeCounter::timeCounter () {
startTime = time.now();
}
long timeCounter::getTimePassed () {
currentTime = time.now();
timeDifference = timeNow - timeStart;
return timeDifference;
}
我试过 clock() / CLOCKS_PER_SECONDS
但结果比一秒还慢。
谁能帮帮我?
非常感谢!
我最近正在编写一个类似的系统来获取游戏引擎的增量时间。
使用 std::chrono
库,这里有一个例子:
#include <iostream>
#include <chrono>
#include <thread>
class timer
{
// alias our types for simplicity
using clock = std::chrono::system_clock;
using time_point_type = std::chrono::time_point < clock, std::chrono::milliseconds > ;
public:
// default constructor that stores the start time
timer()
{
start = std::chrono::time_point_cast<std::chrono::milliseconds>(clock::now());
}
// gets the time elapsed from construction.
long /*milliseconds*/ getTimePassed()
{
// get the new time
auto end = clock::now();
// return the difference of the times
return (end - start).count();
}
private:
time_point_type start;
};
int main()
{
timer t;
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << t.getTimePassed();
std::cin.get();
}