最近工作之余开个新坑,我的老朋友:CMU15-445,这是一门学习数据库的神课,以下便记录我的课程project的实现。
因为课程明确说明了不准把代码上传到开放平台,github之类的网站,因此我的记录只会贴一些关键代码。
0 准备工作
该课程会使用C++来完成project,如果不熟悉C++的同学可以先去学习。
https://15445.courses.cs.cmu.edu/fall2020/project0/
0.1 下载bustub仓库代码
$ git clone https://github.com/cmu-db/bustub.git
0.2 安装编译
进入到bustub目录,依次执行以下命令:
$ git remote add public https://github.com/cmu-db/bustub.git
$ git fetch public
$ git merge public/master
$ sudo ./build_support/packages.sh
- 如果用的是macbook,执行最后一条命令的时候可能会报一些权限相关的错误,把sudo去掉再执行一次
$ mkdir build
$ cd build
$ cmake ..
$ make
1 完成课程
完成project0只需要改动src/include/primer/p0_starter.h 文件
Matrix
- 在构造函数中对 rows,cols 进行赋值,然后为 linear 指针分配空间
- 在析构函数中释放分配给 linear 的空间
RowMatrix
- 在构造函数中给 data_ 分配一个行指针数组,然后初始化指针的值
RowMatrix(int r, int c) : Matrix<T>(r, c) {
data_ = reinterpret_cast<T **>(malloc(sizeof(T *) * r));
for (int i = 0; i < r; i++) {
data_[i] = Matrix<T>::linear + i * c;
}
}
- MatImport 函数会通过数组 arr 来设置矩阵对应的值
void MatImport(T *arr) override {
for (int i = 0; i < Matrix<T>::rows * Matrix<T>::cols; i++) {
Matrix<T>::linear[i] = arr[i];
}
}
RowMatrixOperations
- 实现矩阵的加、乘、GEMM 操作
- 加比较简单,我就不贴代码了,乘的实现如下:
static std::unique_ptr<RowMatrix<T>> MultiplyMatrices(std::unique_ptr<RowMatrix<T>> mat1,
std::unique_ptr<RowMatrix<T>> mat2) {
if (mat1->GetColumns() != mat2->GetRows()) {
return std::unique_ptr<RowMatrix<T>>(nullptr);
}
int rows = mat1->GetRows();
int cols = mat2->GetColumns();
int mat1Cols = mat1->GetColumns();
std::unique_ptr<RowMatrix<T>> res(new RowMatrix<T>(rows, cols));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int sum = 0;
for (int k = 0; k < mat1Cols; k++) {
sum += mat1->GetElem(i, k) * mat2->GetElem(k, j);
}
res->SetElem(i, j, sum);
}
}
return res;
}
2 测试
首先去掉 test/primer/starter_test.cpp 中的 DISABLED_前缀
$ cd build
$ make starter_test
$ ./test/starter_test
Running main() from gmock_main.cc
[==========] Running 3 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 3 tests from StarterTest
[ RUN ] StarterTest.SampleTest
[ OK ] StarterTest.SampleTest (0 ms)
[ RUN ] StarterTest.AddMatricesTest
[ OK ] StarterTest.AddMatricesTest (0 ms)
[ RUN ] StarterTest.MultiplyMatricesTest
[ OK ] StarterTest.MultiplyMatricesTest (0 ms)
[----------] 3 tests from StarterTest (0 ms total)
[----------] Global test environment tear-down
[==========] 3 tests from 1 test suite ran. (0 ms total)
[ PASSED ] 3 tests.
大功告成!
|