减少Cell.Calculate方法的计算时间
可能的使用场景
通常,我们建议用户调用Workbook.CalculateFormula()方法一次,然后获取单个单元格的计算值。 但有时,用户不想计算整个工作簿。 他们只想计算单个单元格。 Aspose.Cells提供CalculationOptions.Recursive属性,您可以设置为false并且它将显著减少单个单元格的计算时间。 因为当递归属性设置为true时,每次调用都会重新计算单元格的依赖项。 但当递归属性为false时,依赖单元格仅计算一次,并且后续调用时不会再次计算。
减少Cell.Calculate()方法的计算时间
以下示例代码说明了CalculationOptions.Recursive属性的用法。 请使用所提供的sample excel file执行此代码并检查其控制台输出。 您会发现将递归属性设置为false后,计算时间明显减少。 请阅读注释以更好地理解此属性。
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// Test calculation time after setting recursive true | |
TestCalcTimeRecursive(true); | |
// Test calculation time after setting recursive false | |
TestCalcTimeRecursive(false); |
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
static void TestCalcTimeRecursive(bool rec) | |
{ | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Load your sample workbook | |
Workbook wb = new Workbook(dataDir + "sample.xlsx"); | |
// Access first worksheet | |
Worksheet ws = wb.Worksheets[0]; | |
// Set the calculation option, set recursive true or false as per parameter | |
CalculationOptions opts = new CalculationOptions(); | |
opts.Recursive = rec; | |
// Start stop watch | |
Stopwatch sw = new Stopwatch(); | |
sw.Start(); | |
// Calculate cell A1 one million times | |
for (int i = 0; i < 1000000; i++) | |
{ | |
ws.Cells["A1"].Calculate(opts); | |
} | |
// Stop the watch | |
sw.Stop(); | |
// Calculate elapsed time in seconds | |
long second = 1000; | |
long estimatedTime = sw.ElapsedMilliseconds / second; | |
// Print the elapsed time in seconds | |
Console.WriteLine("Recursive " + rec + ": " + estimatedTime + " seconds"); | |
} |
控制台输出
这是在我们的机器上使用给定的sample excel file执行以上示例代码的控制台输出。 请注意,您的输出可能不同,但在将递归属性设置为false后经过的时间将始终少于将其设置为true。
Recursive True: 96 seconds
Recursive False: 42 seconds