//本文套的是c#的壳,里面还是c++,功能是遍历大内存和计算,看看时间
//本程序调试通过,拷贝过去,修改命名空间,项目里面允许不安全代码。
//你电脑的剩余内存要足够,要不然,还是会报错
//可参考本人的上一篇文章
using System;
using System.Runtime.InteropServices;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
DateTime DT1 = DateTime.Now;
aaa.Method();
DateTime DT2 = DateTime.Now;
Console.WriteLine(DT2-DT1);
Console.ReadLine();
}
}
public static class aaa
{
static public void Method()
{
unsafe
{
const int m = 200000000;
// 使用AllocHGlobal模拟malloc
IntPtr a = (IntPtr)Marshal.AllocHGlobal(m * sizeof(int));
int* a1 = (int*) a;//精髓在此行,要不然释放内存行会报错
IntPtr b = (IntPtr)Marshal.AllocHGlobal(m * sizeof(int)); // 使用AllocHGlobal模拟malloc
int* b1 = (int*)a;
for (int i = 0; i < m; i++)
{
*a1 = i;
a1++;
}
a1--;
Console.WriteLine(*a1);
a1 = (int*)a;
for (int i = 0; i < m; i++)
{
*b1 = (*a1)*3;
a1++;
b1++;
}
b1--;
Console.WriteLine(*b1);
Marshal.FreeHGlobal(a);//释放内存
Marshal.FreeHGlobal(b);//释放内存
}
}
static public void Method2()//c#
{
const int m = 100000000;
int[] a = new int[m];
int[] b = new int[m];
for (int i = 0; i < m; i++)
{
a[i] = i;
}
Console.WriteLine(a[m - 1]);
for (int i = 0; i < m; i++)
{
b[i] = a[i] * 3;
}
Console.WriteLine(b[m - 1]);
}
}
}