#include <ctime>
#include <iostream>
#include <iomanip>
#include <string>
#include <torch/torch.h>
#include <functional>
#include <map>
#include <complex>

double timer(std::function<torch::Tensor(const torch::Tensor &in)> func, const torch::Tensor &in, torch::Tensor& out) {
  
  std::clock_t start;
  double duration;
  start = std::clock();
  out = func(in);
  duration = (std::clock() - start) / (double)CLOCKS_PER_SEC;

  return duration;
}

int main() {

  int N = 200;
  int nrow = 10000;
  int ncol = 1000;
  torch::set_num_threads(1);

  std::vector<torch::Tensor> input;
  for (int j = 0; j < N; ++j) {
    auto r = torch::randn({nrow, ncol}, torch::dtype(torch::kFloat32));
    auto i = torch::zeros_like(r);
    auto c = torch::stack({r, i}, 2);
    input.push_back(c);
  }

  {
    torch::Tensor o;
    std::map<std::string, double> m_name_time = { {"cpu",0} };
    for (auto c : input) {
      m_name_time["cpu"] +=
          timer([](const torch::Tensor &in) { return torch::ifft(torch::fft(in, 2), 2); }, c, o);
    }

    for(auto nt : m_name_time) {
      std::cout << std::setw(20) << nt.first << " : "  << std::setw(20) << nt.second * 1000 / N << " ms/loop @ N = " << N << "\n";
    }
  }
  
  {
    torch::rand({1, 1}, torch::dtype(torch::kFloat32).device(torch::kCUDA, 0));

    torch::Tensor g, gf, gif, cp;
    std::map<std::string, double> m_name_time = { {"to_gpu",0}, {"fft",0}, {"ifft",0}, {"to_cpu",0} };

    for(auto c : input) {
      m_name_time["to_gpu"]  += timer([](const torch::Tensor &in){return in.cuda();}, c, g);
      m_name_time["fft"]     += timer([](const torch::Tensor &in){return torch::fft(in, 2);}, g, gf);
      m_name_time["ifft"]    += timer([](const torch::Tensor &in){return torch::ifft(in, 2);}, gf, gif);
      m_name_time["to_cpu"]  += timer([](const torch::Tensor &in){return in.cpu();}, gif, cp);
      if(N < 10 and nrow*ncol <10) {
        std::cout << "-----------" << std::endl;
        std::cout << c << std::endl;
        std::cout << g << std::endl;
        std::cout << gf << std::endl;
        std::cout << gif << std::endl;
        std::cout << cp << std::endl;
      }
    }

    for(auto nt : m_name_time) {
      std::cout << std::setw(20) << nt.first << " : "  << std::setw(20) << nt.second * 1000 / N << " ms/loop @ N = " << N << "\n";
    }
  }
}