减少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-Java | |
public static void main(String[] args) throws Exception { | |
// Test calculation time after setting recursive true | |
TestCalcTimeRecursive(true); | |
// Test calculation time after setting recursive false | |
TestCalcTimeRecursive(false); | |
} | |
// -------------------------------------------------- | |
static void TestCalcTimeRecursive(boolean rec) throws Exception { | |
String dataDir = Utils.getDataDir(DecreaseCalculationTime.class); | |
// Load your sample workbook | |
Workbook wb = new Workbook(dataDir + "sample.xlsx"); | |
// Access first worksheet | |
Worksheet ws = wb.getWorksheets().get(0); | |
// Set the calculation option, set recursive true or false as per parameter | |
CalculationOptions opts = new CalculationOptions(); | |
opts.setRecursive(rec); | |
// Start calculating time in nanoseconds | |
long startTime = System.nanoTime(); | |
// Calculate cell A1 one million times | |
for (int i = 0; i < 1000000; i++) { | |
ws.getCells().get("A1").calculate(opts); | |
} | |
// Calculate elapsed time in seconds | |
long second = 1000000000; | |
long estimatedTime = System.nanoTime() - startTime; | |
estimatedTime = estimatedTime / second; | |
// Print the elapsed time in seconds | |
System.out.println("Recursive " + rec + ": " + estimatedTime + " seconds"); | |
} |
控制台输出
这是在我们的计算机上使用给定的sample excel file执行上述示例代码的控制台输出。请注意,您的输出可能有所不同,但在将递归属性设置为false后,经过的时间总是少于将其设置为true。
Recursive true: 51 seconds
Recursive false: 16 seconds