Question

In: Computer Science

Compare C++ speed to Python speed. To compare Execution Time of: c++ vs. Py : //...

Compare C++ speed to Python speed.


To compare Execution Time of: c++ vs. Py :
// this is c++ code // covert this code to python and compare their execution time

#include<time.h>
#include <iostream>
using namespace std;
#include <chrono> //for time
using namespace std::chrono;

void doSomething() //to insert any execution code here to measure its running time
{ int x=6795; // cout << "Enter 4-digit integer x ?\n"; cin >> x;
for (int i = 1000; i < 2000000; i++) //a constant number of iterations
{
if (i % 2) x = i + int(sqrt(x)); else x = i + x * x; //do any computation here
}
}

void computeTime()
{ auto start = high_resolution_clock::now(); //starting time in milli-seconds
doSomething();
auto stop = high_resolution_clock::now(); //stopping time in milli-seconds
auto duration = duration_cast<microseconds>(stop - start); //duration time in milli-seconds
cout << "duration= " << duration.count() << endl;
}

void main()
{
int more = 1;
while (more) { computeTime(); cout << "more? <0,1> "; cin >> more; }
system("pause");
}

==================================================

// ( Python version. Be careful to put correct indentation for Python code below)

#---------- Now Python code to do the same as above code in C++
import math
import datetime

def measureSpeed():

t1 = datetime.datetime.now().microsecond

x = 6795 # cout << "Enter 4-digit integer x ?\n"; cin >> x;
#for (int i = 1000; i < 2000000; i++) //a constant number of iterations
for i in range(1000,2000000,1):
if (i % 2):
x = i + math.sqrt(x) #x = i + int(sqrt(x));
else:
x = i + x * x #do any computation here

t2 = datetime.datetime.now().microsecond

print(t2)
print(t1)
print(t2-t1)


def main():
more=1
while(more):
more = input("Please enter <0 or 1> to stop or continue:\n")
print(f'You entered {more}')
if(more):
measureSpeed()

main()

=====================================================

Solutions

Expert Solution

ANSWER:

  • I have provided the properly commented  and indented code so you can easily copy the code as well as check for correct indentation.
  • I have provided the output image of the code so you can easily cross-check for the correct output of the code.
  • Have a nice and healthy day!!

CODE

  • C++11 CODE
#include<time.h>
#include <iostream>
#include <cmath>
using namespace std;
#include <chrono> //for time
using namespace std::chrono;

void doSomething() //to insert any execution code here to measure its running time
{ 
        int x=6795; // cout << "Enter 4-digit integer x ?\n"; cin >> x;
        for (int i = 1000; i < 2000000; i++) //a constant number of iterations
        {
                if (i % 2) 
                        x = i + int(sqrt(x));
                else
                        x = i + x * x; //do any computation here
        }
}

void computeTime()
{ 
        auto start = high_resolution_clock::now(); //starting time in milli-seconds
        doSomething();
        auto stop = high_resolution_clock::now(); //stopping time in milli-seconds
        auto duration = duration_cast<microseconds>(stop - start); //duration time in milli-seconds
        cout << "duration= " << duration.count() <<" Microseconds" << endl;
}

int main()
{
        int more = 1;
        while (more)
        { 
                computeTime();
                cout << "more? <0,1> ";
                cin >> more;
        }
        system("pause");
}
  • PYTHON CODE
import math
import datetime

def measureSpeed():
    # starting time, using datetime.datetime.now()
    t1 = datetime.datetime.now()
    
    # required code
    x = 6795 # cout << "Enter 4-digit integer x ?\n"; cin >> x;for (int i = 1000; i < 2000000; i++) //a constant number of iterations
    for i in range(1000,2000000,1):
        if (i % 2):
            x = i + math.sqrt(x) #x = i + int(sqrt(x));
        else:
            x = i + x * x #do any computation here
    # end time        
    t2 = datetime.datetime.now()
    
    # calculating duration, in seconds using total_seconds method of timedelta
    duration = (t2-t1).total_seconds()
    # converting seconds to microseconds
    durationMS = duration * (10**6)
    
    # displaying results
    print("duration = {:d} Microseconds".format(int(durationMS)))

# main function
def main():
    more=1
    # while loop, till more is 1
    while(more):
        # calling function measureSpeed
        measureSpeed()
        # prompting user, and converting input to integer using int function
        more = int(input("Please enter <0 or 1> to stop or continue:\n"))

# calling main
main()

OUTPUT IMAGE

  • C++ OUTPUT

  • Python OUTPUT


Related Solutions

***This program is to be created using Python*** Requirements to be numbered in program01.py: Print “This...
***This program is to be created using Python*** Requirements to be numbered in program01.py: Print “This program provides concert seat assignments.” Ask the user their musical preference and take the following actions based on their potential input: Classical – proceed with the program (i.e. move the next requirement) – output a message that states “We do not recognize the musical genre.” Then end the program. Ask the user to enter the following data about themselves: • First Name • Last...
Problem: Write a Python module (a text file containing valid Python code) named p5.py. This file...
Problem: Write a Python module (a text file containing valid Python code) named p5.py. This file must satisfy the following. Define a function named rinsert. This function will accept two arguments, the first a list of items to be sorted and the second an integer value in the range 0 to the length of the list, minus 1. This function shall insert the element corresponding to the second parameter into the presumably sorted list from position 0 to one less...
Python Create a Python script file called hw3.py. Ex. 1. Write a program that inputs numbers...
Python Create a Python script file called hw3.py. Ex. 1. Write a program that inputs numbers from the user until they enter a 0 and computes the product of all these numbers and outputs it. Hint: use the example from the slides where we compute the sum of a list of numbers, but initialize the variable holding the product to 1 instead of 0. print("Enter n") n = int(input()) min = n while n != 0: if n < min:...
What to do: 1. Write a Python program, a1.py with the following characteristics: a) there are...
What to do: 1. Write a Python program, a1.py with the following characteristics: a) there are at least 40 lines of comments and 40 lines of code (1 point) b) the problem is described at the top of the program in a readable fashion (1 point) c) the code includes at least one instance of each of the five learning objectives listed above. (3 points) d) the code solves the problem. This may be assessed in part by a 'code...
What to do: 1. Write a Python program, a1.py with the following characteristics: a) there are...
What to do: 1. Write a Python program, a1.py with the following characteristics: a) there are at least 40 lines of comments and 40 lines of code (1 point) b) the problem is described at the top of the program in a readable fashion (1 point) c) the code includes at least one instance of each of the five learning objectives listed above. (3 points) d) the code solves the problem. This may be assessed in part by a 'code...
Draw a position-vs-time, velocity-vs-time, and acceleration-vs-time graph for each of the following objects: 1. A car...
Draw a position-vs-time, velocity-vs-time, and acceleration-vs-time graph for each of the following objects: 1. A car traveling in a straight line at a constant speed. 2. A ball rolling down a hill, getting faster as time goes by. 3. A rock that is tossed straight up in the air before coming back down to its starting point.
Java, Python, and C++ are three of the most useful programming languages to learn. Compare the...
Java, Python, and C++ are three of the most useful programming languages to learn. Compare the functionalities of all three programming languages. Why would you choose one language over another? Provide code examples demonstrating their usefulness in a real-world scenario.
Compare the following pairs of methods/techniques: Time stamping vs. optimistic methods in distributed systems
Compare the following pairs of methods/techniques: Time stamping vs. optimistic methods in distributed systems
Assignment Requirements Write a python application that consists of two .py files. One file is a...
Assignment Requirements Write a python application that consists of two .py files. One file is a module that contains functions used by the main program. NOTE: Please name your module file: asgn4_module.py The first function that is defined in the module is named is_field_blank and it receives a string and checks to see whether or not it is blank. If so, it returns True, if not it return false. The second function that is defined in the module is named...
"""    CS 125 - Intro to Computer Science    File Name: CS125_Lab1.py    Python Programming...
"""    CS 125 - Intro to Computer Science    File Name: CS125_Lab1.py    Python Programming    Lab 1    Name 1: FirstName1 LastName1    Name 2: FirstName2 LastName2    Description: This file contains the Python source code for deal or no deal. """ class CS125_Lab1(): def __init__(self): # Welcome user to game print("Let's play DEAL OR NO DEAL")    # Define instance variables and init board self.cashPrizes = [.01, .50, 1, 5, 10, 50, 100, 250, 500, 1000, 5000,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT