내가 자바
에
public class UserSearchMain {
static class Person {
int id;
int dateOfBirth;
static Person[] generatePeople(int num) {
Random rand = new Random();
Person[] people = new Person[num];
for (int i = 0; i < num; i++) {
Person p = new Person();
p.id = i;
p.dateOfBirth = rand.nextInt(80 * 365); // any day for 80 years.
people[i] = p;
}
return people;
}
}
public static void main(String... args) {
Person[] people = Person.generatePeople(5000);
List<List<Person>> peopleByDOB = new ArrayList<List<Person>>();
for (Person person : people) {
int dob = person.dateOfBirth;
while (peopleByDOB.size() <= dob) peopleByDOB.add(new ArrayList<Person>());
peopleByDOB.get(dob).add(person);
}
Random rand = new Random();
int warmup = 12 * 1000;
int runs = 1000 * 1000;
long start = 0;
for (int i = -warmup; i < runs; i++) {
if (i == 0) start = System.nanoTime();
int dayToSearch = rand.nextInt(80 * 365);
for (int j = Math.max(0, dayToSearch - 7); j <= dayToSearch + 7 && j < peopleByDOB.size(); j++) {
List<Person> peopleWithCloseDOM = peopleByDOB.get(j);
}
}
long time = System.nanoTime() - start;
System.out.printf("Each search took an average of %,d ns%n", time/runs);
}
}
인쇄
Each search took an average of 85 ns
를 작성합니다 종종 언어의 선택보다 더 중요한 사용하는 algorithim.
EDIT : 원래의 질문에 대한 답변으로, 같은 알고리즘을 사용하여 C++에서 더 빠르게 만들 수 있습니까? 나는 네가 추측 하겠지만 많이는 아니야.
더 빠르게 처리하려면 여러 스레드를 사용할 수 있습니다.
public static void main(String... args) throws ExecutionException, InterruptedException {
Person[] people = Person.generatePeople(5000);
final List<List<Person>> peopleByDOB = new ArrayList<List<Person>>();
for (Person person : people) {
int dob = person.dateOfBirth;
while (peopleByDOB.size() <= dob) peopleByDOB.add(new ArrayList<Person>());
peopleByDOB.get(dob).add(person);
}
final int runs = 10 * 1000 * 1000;
long start = System.nanoTime();
int processors = Runtime.getRuntime().availableProcessors();
ExecutorService service = Executors.newFixedThreadPool(processors);
List<Future> futures = new ArrayList<Future>();
for (int i = 0; i < processors; i++) {
futures.add(service.submit(new Runnable() {
@Override
public void run() {
Random rand = new Random();
for (int i = 0; i < runs; i++) {
int dayToSearch = rand.nextInt(80 * 365);
for (int j = Math.max(0, dayToSearch - 7); j <= dayToSearch + 7 && j < peopleByDOB.size(); j++) {
List<Person> peopleWithCloseDOM = peopleByDOB.get(j);
}
}
}
}));
}
for (Future future : futures) {
future.get();
}
service.shutdown();
double timeSec = (System.nanoTime() - start)/1e9;
double rate = processors * runs/timeSec/1e6;
System.out.printf("The search throughput was %.1f million per second%n", rate);
}
인쇄 됨 약 31 ns의 평균을 의미
The search throughput was 32.4 million per second
.
클래식 알고리즘을 사용하는 것이 더 빠르지 않습니까? SA는 멋지지만 실제로 그 용도로 왜 필요한지는 알 수 없습니다. – harold
@harold : 분명히 'SA가 냉각되고있다'는 뜻입니까? –
나는 그 알고리즘에 익숙하지 않지만, 5,000 개체의 데이터 세트를위한 15 초는 ** 매우 ** 길다. – assylias