概要:

  众所周知,用C#做界面比C++开发效率要高得多,但在有性能问题的情况下不得不将部分模块使用C++,这时就需要使用C#与C++混合编程。本文给出了两种混合编程的方法以及性能对比。

开发环境:

  ThinkPad T430 i5-3230M 2.6G 8G,Win7 64Bit,VS2013(C++开发设置),C++,C#都采用x64平台,性能验证使用Release版本。

测试纯C++项目性能:

  1. 新建空解决方案:文件|新建|项目|已安装|模板|其他项目类型|Visual Studio解决方案|空白解决方案

  2. 新建PureCpp项目:右击解决方案|添加|新建项目|已安装|Visual C++|Win32控制台程序,按缺省设置生成项目

  3. 在配置管理器中新建x64平台,删除其他平台

  4. 新建CppFunction,并添加测试代码,完整代码如下,程序结果:Result: 1733793664 Elapsed: 109

// CppFunction.h
#pragma once
class CppFunction
{
public:
    CppFunction(){}
    ~CppFunction(){}

    int TestFunc(int a, int b);
};

// CppFunction.cpp
#include "stdafx.h"
#include "CppFunction.h"

class CCalc
{
public:
    CCalc(int a, int b)
    {
        m_a = a;
        m_b = b;
    }

    int Calc()
    {
        if (m_a % 2 == 0){
            return m_a + m_b;
        }
        if (m_b % 2 == 0){
            return m_a - m_b;
        }
        return m_b - m_a;
    }

private:
    int m_a;
    int m_b;
};

int CppFunction::TestFunc(int a, int b)
{
    CCalc calc(a, b);
    return calc.Calc();
}

// PureCpp.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include "CppFunction.h"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    DWORD start = ::GetTickCount();
    CppFunction cppFunction;
    int result = 0;
    for (int i = 0; i < 10000; i++){
        for (int j = 0; j < 10000; j++){
            result += cppFunction.TestFunc(i, j);
        }
    }
    DWORD end = ::GetTickCount();

    cout << "Result: " << result << " Elapsed: " << end - start << endl;

    return 0;
}
View Code

相关文章:

  • 2021-12-10
  • 2022-02-10
  • 2021-12-03
  • 2022-12-23
猜你喜欢
  • 2022-01-02
  • 2022-12-23
  • 2021-11-02
  • 2021-08-21
  • 2021-12-22
  • 2022-12-23
相关资源
相似解决方案