memory_test.cc 2.0 KB
Newer Older
L
liaogang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "paddle/memory/memory.h"
L
liaogang 已提交
16
#include "gtest/gtest.h"
L
liaogang 已提交
17 18
#include "paddle/platform/place.h"

L
liaogang 已提交
19 20 21 22
template <typename T>
inline bool is_aligned(T *p, size_t n = alignof(T)) {
  return 0 == (reinterpret_cast<uintptr_t>(p) % n);
}
L
liaogang 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36

TEST(BuddyAllocator, CPUAllocation) {
  void *p = nullptr;

  EXPECT_EQ(p, nullptr);

  paddle::platform::CPUPlace cpu;
  p = paddle::memory::Alloc(cpu, 4096);

  EXPECT_NE(p, nullptr);

  paddle::memory::Free(cpu, p);
}

L
liaogang 已提交
37 38 39
TEST(BuddyAllocator, CPUMultAlloc) {
  paddle::platform::CPUPlace cpu;

L
liaogang 已提交
40
  std::vector<void *> ps;
L
liaogang 已提交
41 42
  ps.reserve(8);

L
liaogang 已提交
43 44
  for (auto size :
       {128, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304}) {
L
liaogang 已提交
45 46 47 48
    ps.emplace_back(paddle::memory::Alloc(cpu, size));
  }

  for (auto p : ps) {
L
liaogang 已提交
49
    EXPECT_EQ(is_aligned(p, 32), true);
L
liaogang 已提交
50 51 52 53
    paddle::memory::Free(cpu, p);
  }
}

L
liaogang 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
#ifndef PADDLE_ONLY_CPU

TEST(BuddyAllocator, GPUAllocation) {
  void *p = nullptr;

  EXPECT_EQ(p, nullptr);

  paddle::platform::GPUPlace gpu(0);
  p = paddle::memory::Alloc(gpu, 4096);

  EXPECT_NE(p, nullptr);

  paddle::memory::Free(gpu, p);
}

L
liaogang 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
TEST(BuddyAllocator, GPUMultAlloc) {
  paddle::platform::GPUPlace gpu;

  std::vector<void *> ps;
  ps.reserve(8);

  for (auto size :
       {128, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304}) {
    ps.emplace_back(paddle::memory::Alloc(gpu, size));
  }

  for (auto p : ps) {
    EXPECT_EQ(is_aligned(p, 32), true);
    paddle::memory::Free(gpu, p);
  }
}

L
liaogang 已提交
86
#endif  // PADDLE_ONLY_CPU