现在的位置: 首页 > 综合 > 正文

通过比较时间戳避免重复生成文件

2012年07月24日 ⁄ 综合 ⁄ 共 2517字 ⁄ 字号 评论关闭

    最近在项目中有这样一个需求,为了分析某些文件的产权信息,需要对项目中所有的文件生成相对应的.ip文件,当在eclipse中package explorer中selectedChange的时候,调用该project/folder/file下所有文件,生成相应的.ip文件。但是问题出现了,每次package explorer中selectedChange的时候,都需要生成一次.ip文件,而大多数情况,这个都是没有必要的(对于已经Build过的文件,如果该文件上一次Build后没有改变,Build是没有意义的),对于较大的项目,这在效率上是难以接受的,为了对于已经Build,并且在Build后没有改变的文件,我们完全可以不再Build,在这里,我们可以借用ant的解决方案:Ant通过比较类文件和源文件的时间戳来最小化编译工作。类似的,我们可以通过比较Build生成的文件和原文件的时间戳来实现:如果原文件修改时间在Build生成文件修改时间之前,则不需要Build,否则需要Build(不存在的文件时间戳设为-1)。     抽象出来,这个解决方案还是挺有用的,在很多场合可以通过这种方法判断是否需要生成新的文件,避免重复生成文件,提高了效率。

下面是程序片段:

package com.ibm.crl.ariadne.ipmanagement.util;

import java.io.File; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path;

public class BuildUtil {  /**    * @author suqiang   * @param artifact   * @return the value whether the artifact need to be Built   */  public static boolean needBeBuilt(IFile artifact){      //if the file is not the java/htm/gif/jpg/jar file, it need not built.   String artifactName = artifact.getName();   if(!(artifactName.endsWith(".java")|artifactName.endsWith(".jar")))    return false;

  IPath relativeProjectPath = artifact.getProjectRelativePath();   IPath projectFullPath = artifact.getProject().getFullPath();      IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();     IFile ipFile = (IFile)root.getFile(new Path(projectFullPath.toString()+"/.ip/"+relativeProjectPath.toString()+".ip"));

  //transform from IFile to File in order to get the lastModified time,the method getLocalTimeStamp of IResource is unreliable   //More in eclipse document:Note that due to varying file system timing granularities,   //this value is not guaranteed to change every time the file is modified.   File artifactFile = artifact.getLocation().toFile();   File ipFileFile = ipFile.getLocation().toFile();

  long buildFileTimeStamp = ipFileFile.lastModified();   long sourceTimeStamp = artifactFile.lastModified();      //if the artifact has been built before and the artifact itself is not modified,it needn't be build again    if(buildFileTimeStamp>=sourceTimeStamp)    return false;   else    return true;  } }

 

优化前: The build process cost 31828ms  (core) The build process cost 31109ms  (core) The build process cost 114640ms (ui) The build process cost 113406ms (ui) 优化后: The ip file is exist: The build process cost 94ms  (core) The build process cost 78ms  (core) The build process cost 374ms (ui) The build process cost 359ms (ui) delete the ip file: The build process cost 32219ms  (core) The build process cost 37828ms  (core) The build process cost 133906ms (ui) The build process cost 134438ms (ui)

以下是一些测试的结果数据(取了两个非常庞大的项目core and ui)

抱歉!评论已关闭.