In: Computer Science
For the following program segments, write a program that shows the estimated runtime for each piece. Run it on your computer when n=1, 10, 100, 1000, 10000, 100000, 1000000 for ten times each so that you can observe the differences in performance among these segments.
Segment1: for (sum=0, i=1; i<=n; i++)
sum = sum + i;
Segment2: for (sum=0, i=1; i<=n; i++)
for (j=1; j<=i; j++)
sum++;
Segment3: sum= n * (n+1)/2

public class ShowTimes {
public static long sum1(int n) {
long start = System.nanoTime();
int sum, i;
for (sum = 0, i = 1; i <= n; i++)
sum = sum + i;
long end = System.nanoTime();
return (end - start);
}
public static long sum2(int n) {
long start = System.nanoTime();
int sum, i, j;
for (sum = 0, i = 1; i <= n; i++)
for (j = 1; j <= i; j++)
sum++;
long end = System.nanoTime();
return (end - start);
}
public static long sum3(int n) {
long start = System.nanoTime();
int sum = n * (n + 1) / 2;
long end = System.nanoTime();
return (end - start);
}
public static void main(String[] args) {
int sizes[] = new int[] { 1, 10, 100, 1000, 10000, 100000, 1000000 };
System.out.printf("%-15s%-10s%-10s%-10s\n", "InputSize", "Segment1", "Segment2", "Segment3");
for (int size : sizes) {
System.out.printf("%-15d%-10d%-10d%-10d\n", size, sum1(size), sum2(size), sum3(size));
}
}
}
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.