gpt4 book ai didi

c++ - 从单个持续时间和比率计算两个持续时间的正确方法

转载 作者:太空宇宙 更新时间:2023-11-04 12:54:17 24 4
gpt4 key购买 nike

我已经实现了一种计算开启和关闭时间周期性行为的方法,使用由 std::chrono::duration 值和占空比 float 给出的周期。这显示在下面的代码块中。持续时间和占空比的值仅在运行时提供,因此我认为使用 std::ratio 是不可能的。谁能建议一种更简洁的方法来实现这一点?

PeriodicPulse(const Period period, const float duty): mRunning(false)
{
if (duty < 0 || duty > 1) {
throw std::runtime_error("Duty value should be between 0-1.");
}
auto tempTime = std::chrono::duration<float, decltype(period)::period>(period.count() * duty);
mOnTime = std::chrono::duration_cast<decltype(mOnTime)>(tempTime);
tempTime = std::chrono::duration<float, decltype(period)::period>(period.count() * (1 - duty));
mOffTime = std::chrono::duration_cast<decltype(mOffTime)>(tempTime);
}

最佳答案

您的代码在我看来很好,尤其是当您的测试表明它正在执行您想要的操作时。下面我提供了一些风格上的清理,并将构造函数放在 PeriodicPulse 的上下文中:

struct PeriodicPulse
{
using Duration = std::chrono::milliseconds;

bool mRunning;
Duration mOnTime;
Duration mOffTime;

template <class Rep, class Period>
PeriodicPulse(const std::chrono::duration<Rep, Period> period, const float duty)
: mRunning(false)
{
if (duty < 0 || duty > 1) {
throw std::runtime_error("Duty value should be between 0-1.");
}
using namespace std::chrono;
duration<float, Period> tempTime = period * duty;
mOnTime = duration_cast<Duration>(tempTime);
tempTime = period * (1 - duty);
mOffTime = duration_cast<Duration>(tempTime);
}
};
  • 我已重命名 Periodstd::chrono::duration<Rep, Period>表明它实际上预期具有类型持续时间,但变量名称为 period描述持续时间的功能。这也用于限制(我假设的)是一个过于通用的模板参数。 (我的假设可能不正确)

  • 在函数作用域中,我发现重复使用了 std::chrono::过于冗长且难以阅读。我更喜欢局部函数 using namespace std::chrono; .你可能会有不同的感受。

  • 我替换了:


auto tempTime = std::chrono::duration<float, decltype(period)::period>(period.count() * duty);

与:

duration<float, Period> tempTime = period * duty;

这重用了 Period从重写的参数类型中,避免不必要地使用 .count()成员函数。

  • 对于mOnTime的分配和 mOffTime我创建了一个 Duration别名这样我就不用说了 decltype(mOnTime) . decltype(mOnTime)没问题, 我只是找到 Duration在此上下文中更具可读性,我仍然可以在一个地方更改这些成员的类型。

  • duration_cast给予 tempTime 时没有必要它的第二个值,因为存在到基于 float 的持续时间的隐式转换。我又一次避免了 .count()成员函数,以便保持在 <chrono> 的类型安全保护范围内类型系统。

我是这样测试的:

#include "date/date.h"
#include <chrono>
#include <iostream>

int
main()
{
using date::operator<<;
using namespace std;
using namespace std::chrono;
using P = duration<int, ratio<1, 30>>;
PeriodicPulse p{P{3}, .2};
cout << p.mOnTime << '\n';
cout << p.mOffTime << '\n';
}

哪些输出:

20ms
80ms

这与我使用您的原始代码得到的答案相同。

"date/date.h" 的使用没有必要。这就是我偷懒流出p.mOnTimep.mOffTime .

关于c++ - 从单个持续时间和比率计算两个持续时间的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47364799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com