ebsynth代码源码分析

最近接到了优化ebsynth性能的任务。对于一个新的算法,要优化它的性能,我觉得要从三步来分析

首当其冲的是要看懂代码,算法到底是怎么跑的,实现了什么功能,怎么实现的。

接着在不借助性能分析工具的情况下通读代码,把感觉像是性能瓶颈,算法内核的地方记录下来

再用性能分析优化工具分析出确切的位置,思考为什么这个地方会是瓶颈,怎么优化。

jamriska/ebsynth: Fast Example-based Image Synthesis and Style Transfer (github.com)

 

接下来进入正题。

 

ebsynth_cuda_memarray2.h文件

 

复制代码
// This software is in the public domain. Where that dedication is not
// recognized, you are granted a perpetual, irrevocable license to copy
// and modify this file as you see fit.

#ifndef EBSYNTH_CUDA_MEMARRAY2_H_
#define EBSYNTH_CUDA_MEMARRAY2_H_

#include "jzq.h"
#include "ebsynth_cuda_check.h"

template<typename T>
struct MemArray2 //可以看成是类似GPU的内存数组
{
  T* data; //数组的开头指针
  int width; //宽度
  int height; //长度

  MemArray2() : width(0),height(0),data(0) {};

  MemArray2(const V2i& size) //V2i : Vec<2,int> 
  {
    width = size(0);
    height = size(1);
    checkCudaError(cudaMalloc(&data,width*height*sizeof(T)));
  }

  MemArray2(int _width,int _height)
  {
    width = _width;
    height = _height;
    checkCudaError(cudaMalloc(&data,width*height*sizeof(T)));//为data在GPU中申请一块大小为width*height的内存
  }
  /*
  int       __device__ operator()(int i,int j)
  {
    return data[i+j*width];
  }

  const int& __device__ operator()(int i,int j) const
  {
    return data[i+j*width];
  }
  */

  void destroy()
  {
    checkCudaError( cudaFree(data) ); //销毁内存
  }
};

template<typename T>
void copy(MemArray2<T>* out_dst,const Array2<T>& src)
{
  assert(out_dst != 0);//查看out_dst是否为空,如果为空则弹出报错并退出程序
  MemArray2<T>& dst = *out_dst;    //
  assert(dst.width == src.width());//检查长宽
  assert(dst.height == src.height());
   
  checkCudaError(cudaMemcpy(dst.data, src.data(), src.width()*src.height()*sizeof(T), cudaMemcpyHostToDevice)); //如果长宽都相等,就把CPU内存拷贝到GPU内存当中。
}

template<typename T>
void copy(Array2<T>* out_dst,const MemArray2<T>& src) //同上,不过是从GPU拷贝回CPU内存
{
  assert(out_dst != 0);
  const Array2<T>& dst = *out_dst;
  assert(dst.width() == src.width);
  assert(dst.height() == src.height);

  checkCudaError(cudaMemcpy((void*)dst.data(),src.data, src.width*src.height*sizeof(T), cudaMemcpyDeviceToHost));
}

#endif
复制代码

 

  看着看着发现一堆函数模板类模板。。我觉得一行一行看下来可能不太行,以现在的实力得先找到主功能的实现才行。

posted @   白与花糖  阅读(271)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示