I have the same program written in both C++ and Java. For C++ I am using VS 2019 and for Java using Eclipse 2019-03.
Here is the program in C++.
#define InputSize 500000
int FindDuplicate::FindDuplicateNaive(int* input, int size)
{
int j;
for (int i = 0; i < size-1; i++)
{
for ( j= i+1; j < size; j++)
{
if (input[i] == input[j])
return input[i];
}
}
return -1;
}
int* FindDuplicate::CreateTestCase(int size)
{
int* output = new int[size];
int i;
for ( i= 0; i < size-1; i++)
{
output[i] = i + 1;
}
output[i] = i;
return output;
}
int main()
{
int* input= FindDuplicate::CreateTestCase(InputSize);
auto start = std::chrono::system_clock::now();//clock start
int output = FindDuplicate::FindDuplicateNaive(input, InputSize);
auto end = std::chrono::system_clock::now();//clock end
cout<<"Output is: "<<output<<endl;
std::chrono::duration<double> elapsed_seconds = end - start;
cout<< "elapsed time: " << elapsed_seconds.count() << "s\n";
}
Here is the Java program...
public class FindDuplicate {
public static int FindDuplicateNaive(int[] input) {
for (int i = 0; i < input.length - 1; i++) {
for (int j = i + 1; j < input.length; j++) {
if (input[i] == input[j])
return input[i];
}
}
return -1;
}
public static int[] CreateTestCase(int n) {
// 1, 2, 3, 4, 5, 1 = n = 6
int[] output = new int[n];
int i;
for (i = 0; i < n - 1; i++) {
output[i] = i + 1;
}
output[i] = i;
return output;
}
public static void main(String[] args)
{
//Here also args[0] is 5,00,000
int number = Integer.parseInt(args[0]);
int[] input = CreateTestCase(number);
long start = System.currentTimeMillis();
int output = FindDuplicateNaive(input);
long end = System.currentTimeMillis();
System.out.println("Total time taken is: " + (end - start) / 1000.0 + " secs");
System.out.println(output);
}
You will be shocked to know the time taken by the same program the same input in both c++ and Java.
In Java:
Toal time taken is: 41.876 secs
499999
In CPP:
After enabling the optimization and in release mode,
Output is: 499999
elapsed time: 64.0293s
Any thought on this, what could be the reason? Why Java is taking on 41.876 secs whereas CPP take 64.0293 sec??