让我们假设 Alice 和 Bob 被分配,例如,实现一个函数,返回公历给定日期的星期几,假设指定的日期有效并且属于公历。
是否有被广泛接受的指南(或最佳实践),可以让我们判断谁的代码更好,为什么?
爱丽丝:
int getDayOfWeek(int day, int month, int year)
{
int monthBias[] = { 0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5 };
int yearsBefore = year - 1;
unsigned int result = yearsBefore + yearsBefore / 4 - yearsBefore / 100 + yearsBefore / 400 + monthBias[month - 1] + day;
if (year % 4 == 0 && month > 2 && (year % 100 != 0 || year % 400 == 0))
++result;
return result % 7;
}
鲍勃:
enum DayOfWeek
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
count
};
inline int getLeapYearsBefore(int year)
{
int yearsBefore = year - 1;
return yearsBefore / 4 - yearsBefore / 100 + yearsBefore / 400;
}
inline bool isLeapYear(int year)
{
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
using namespace std;
template <typename T, size_t n>
constexpr size_t arraySize(T (&)[n]) { return n; }
DayOfWeek getDayOfWeek(int day, int month, int year)
{
const int
commonYear[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
leapYear[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
daysInCommonYear = accumulate(commonYear, commonYear + arraySize(commonYear), 0),
daysInLeapYear = accumulate(leapYear, leapYear + arraySize(leapYear), 0),
yearsBefore = year - 1,
leapYearsBefore = getLeapYearsBefore(year),
commonYearsBefore = yearsBefore - leapYearsBefore;
auto kindOfYear = isLeapYear(year) ? leapYear : commonYear;
unsigned int result =
(leapYearsBefore * daysInLeapYear
+ commonYearsBefore * daysInCommonYear
+ accumulate(kindOfYear, kindOfYear + month - 1, day)) % DayOfWeek::count;
return static_cast<DayOfWeek>(result);
}
性能比较并没有为 Alice 的代码带来可检测的优势,因为我试图衡量 Alice 和 Bob 的实现的性能差异,但失败了(使用 high_resolution_clock::now()
和 duration_cast<nanoseconds>(end - start)
)——至少我可以告诉差异小于 0.5%(500 万次通话的平均通话时长)。
最佳答案
如果您正在寻找指南,我建议您阅读 Stroustrup 的 C++ 编程语言书。
但简而言之,这是两种不同的方法:
爱丽丝方法(为什么要使用它): 用于需要高性能的程序的简单方法 - 一个功能(一次调用) - 仅在需要时声明变量 - 使用已知大小的静态分配 vector - 没有详尽使用对象拷贝。
Bob 方法(为什么要使用它):
它基于分而治之的策略。 - 每个函数负责一个任务(如果你想在未来维护代码很有用) - 用于其他目的的高度可重用代码。
关于c++ - 实现功能的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31240833/