有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java计时哪一种添加到树集和哈希集更快?

我有一个树集和一个散列集,我想打印出这两个时间所需的时间。要添加到这两个文件中的txt文件。 到目前为止,我只能记录这两方面的时间,任何指导或帮助

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class Timer {
public static void main(String[] args) throws FileNotFoundException {

    Calendar    startTime    =    Calendar.getInstance();
    Set<String> hSet = new HashSet<String>();
    Set<String> tSet = new TreeSet<String>();

    try{
        File in = new File("C:\\Users\\Ceri\\Desktop\\war-and-peace.txt");
        Scanner s = new Scanner(in);
        while(s.hasNext()){
            String temp = s.next();
            hSet.add(temp);
            tSet.add(temp);
        }

    }catch(FileNotFoundException    e){
        System.out.println("File not found");
    }

    Calendar    endTime    =    Calendar.getInstance();
    double    consumedTime    =    (endTime.getTimeInMillis()    -
    startTime.getTimeInMillis())    /    1000.0;
    System.out.println("Consumed    time:"        +    consumedTime);

}

}


共 (1) 个答案

  1. # 1 楼答案

    创建一个测试Set所需时间的函数,然后用每种集合调用它:

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Calendar;
    import java.util.HashSet;
    import java.util.Scanner;
    import java.util.Set;
    import java.util.TreeSet;
    
    public class Timer {
        public static void main(String[] args) throws FileNotFoundException {
            test("HashSet time: " , new HashSet<String>());
            test("TreeSet time: " , new TreeSet<String>());
        }
    
        private void test(String label, Set set) {
    
            Calendar    startTime    =    Calendar.getInstance();
    
            try{
                File in = new File("C:\\Users\\Ceri\\Desktop\\war-and-peace.txt");
                Scanner s = new Scanner(in);
                while(s.hasNext()){
                    String temp = s.next();
                    set.add(temp);  // <==== Note
                }
    
            }catch(FileNotFoundException    e){
                System.out.println("File not found");
            }
    
            // (I didn't try to fix this truly bizarre indentation / line breaking)
            Calendar    endTime    =    Calendar.getInstance();
            double    consumedTime    =    (endTime.getTimeInMillis()    -
            startTime.getTimeInMillis())    /    1000.0;
            System.out.println(label        +    consumedTime);
        }
    }
    

    你可以通过其他方式来改善它:

    1. 在将数据添加到Set之前,请将文件读取一次,这样就不会用文件性能信息清洗Set性能信息

    2. 让函数返回经过的时间并显示增量

    3. 多次调用该函数,使其不只是每次调用一次,而是跟踪平均值/最差示例/最佳示例

    。。。等等