【发布时间】:2012-08-30 19:57:12
【问题描述】:
我发现 7-zip 很棒,我想在 .net 应用程序上使用它。我有一个 10MB 的文件 (a.001),它需要:
2 秒编码。
如果我能在 c# 上做同样的事情,那就太好了。我已经下载了http://www.7-zip.org/sdk.html LZMA SDK c# 源代码。我基本上将 CS 目录复制到了 Visual Studio 中的控制台应用程序中:
然后我编译,一切顺利编译。所以在输出目录上我放置了文件a.001,大小为10MB。关于我放置的源代码中的主要方法:
[STAThread]
static int Main(string[] args)
{
// e stands for encode
args = "e a.001 output.7z".Split(' '); // added this line for debug
try
{
return Main2(args);
}
catch (Exception e)
{
Console.WriteLine("{0} Caught exception #1.", e);
// throw e;
return 1;
}
}
当我执行控制台应用程序时,应用程序运行良好,我在工作目录中得到了输出 a.7z。 问题是它需要很长时间。执行大约需要 15 秒! 我也尝试过https://stackoverflow.com/a/8775927/637142 的方法,它也需要很长时间。为什么比实际程序慢 10 倍?
还有
即使我设置为只使用一个线程:
仍然需要更少的时间(3 秒对 15 秒):
(编辑)另一种可能性
可能是因为 C# 比汇编或 C 慢吗?我注意到该算法做了很多繁重的操作。例如比较这两个代码块。他们都做同样的事情:
C
#include <time.h>
#include<stdio.h>
void main()
{
time_t now;
int i,j,k,x;
long counter ;
counter = 0;
now = time(NULL);
/* LOOP */
for(x=0; x<10; x++)
{
counter = -1234567890 + x+2;
for (j = 0; j < 10000; j++)
for(i = 0; i< 1000; i++)
for(k =0; k<1000; k++)
{
if(counter > 10000)
counter = counter - 9999;
else
counter= counter +1;
}
printf (" %d \n", time(NULL) - now); // display elapsed time
}
printf("counter = %d\n\n",counter); // display result of counter
printf ("Elapsed time = %d seconds ", time(NULL) - now);
gets("Wait");
}
输出
c#
static void Main(string[] args)
{
DateTime now;
int i, j, k, x;
long counter;
counter = 0;
now = DateTime.Now;
/* LOOP */
for (x = 0; x < 10; x++)
{
counter = -1234567890 + x + 2;
for (j = 0; j < 10000; j++)
for (i = 0; i < 1000; i++)
for (k = 0; k < 1000; k++)
{
if (counter > 10000)
counter = counter - 9999;
else
counter = counter + 1;
}
Console.WriteLine((DateTime.Now - now).Seconds.ToString());
}
Console.Write("counter = {0} \n", counter.ToString());
Console.Write("Elapsed time = {0} seconds", DateTime.Now - now);
Console.Read();
}
输出
注意 c# 慢了多少。这两个程序都在发布模式下从 Visual Studio 外部运行。也许这就是为什么在 .net 中比在 c++ 中花费更长的时间的原因。
我也得到了相同的结果。就像我刚刚展示的示例一样,C# 慢了 3 倍!
结论
我似乎不知道是什么导致了问题。我想我会使用 7z.dll 并从 c# 调用必要的方法。执行此操作的库位于:http://sevenzipsharp.codeplex.com/ 这样我就使用了与 7zip 相同的库:
// dont forget to add reference to SevenZipSharp located on the link I provided
static void Main(string[] args)
{
// load the dll
SevenZip.SevenZipCompressor.SetLibraryPath(@"C:\Program Files (x86)\7-Zip\7z.dll");
SevenZip.SevenZipCompressor compress = new SevenZip.SevenZipCompressor();
compress.CompressDirectory("MyFolderToArchive", "output.7z");
}
【问题讨论】:
-
只是猜测 - 零售与调试有什么区别?
-
我尝试在发布时破坏相同的东西,但没有区别:(
-
如果您给应用一个预热期(例如运行 5 次迭代,然后进行分析),是否有任何改进。
-
认为您为 c# 发布了错误的屏幕截图(我对结果很好奇)。
-
Cpp 44 秒,c# 153 秒。我希望 cpp 在某些方面会胜过 c#,但是这个练习相当于简单的带有原始类型的汇编指令(甚至 IL 代码也演示了这一点)。我怀疑 cpp 编译器是否正在优化循环,否则它会立即执行(也不能解释 7z 的性能差异)。我很想知道有什么区别;可能对调整 .Net 应用程序很有见地。
标签: c# performance compression 7zip lzma