My C++ program seems to be lagging behind in speed compared to the JavaScript code I

My project involves using the same data. In my C++ code, it takes 17 seconds to train 100 data points, while in the JavaScript code from this specific project

https://github.com/CodingTrain/Toy-Neural-Network-JS, it only takes about 10 seconds to train 2400 data points. I really need some help figuring out what's wrong because I need to finish my undergraduate thesis.

I've already built two projects, and one of them (this one) is a neural network in C++ based on that JavaScript code (kind of), but it's still producing the same results.

NeuralNetwork::NeuralNetwork(int a,int b,int c)
{
    this->numInput = a;
    this->numHidden = b;
    this->numOutput = c;
    std::vector<double> vec(a, 0.1);
    for (int i = 0; i < b; ++i) {
        this->weightIH.push_back(vec);
    }
    std::vector<double> vec2(b, 0.1);
    for (int i = 0; i < c; ++i) {
        this->weightHO.push_back(vec2);
    }

}


NeuralNetwork::~NeuralNetwork()
{
}

std::vector<double> NeuralNetwork::tambahbias(std::vector<double> a) {
    int size = a.size();
    for (int i = 0; i < size; ++i) {
        a[i] = a[i] + 1;
    }

    return a;
}

std::vector<double> NeuralNetwork::activate(std::vector<double> a) {
    int size = a.size();
    for (int i = 0; i < size; ++i) {
        a[i] = a[i] / (1 + abs(a[i]));
    }
    return a;
}

std::vector<double> NeuralNetwork::derivation(std::vector<double> a) {
    int size = a.size();
    for (int i = 0; i < size; ++i) {
        a[i] = a[i] * (1 - a[i]);
    }
    return a;
}

std::vector<double> NeuralNetwork::hitungError(std::vector<double> a, std::vector<double> b) {
    int size = a.size();
    for (int i = 0; i < size; ++i) {
        a[i] = b[i] - a[i];
    }

    return a;
}


    void NeuralNetwork::train(std::vector<double> a, std::vector<double> target) {
        std::vector<double> hidden(numHidden);
        for (int i = 0; i < numHidden; ++i) {
            for (int j = 0; j < numInput; ++j) {
                hidden[i] += a[j] * weightIH[i][j];
            }
        }
        hidden = tambahbias(hidden);
        hidden = activate(hidden);
        std::vector<double> output(numOutput);
        for (int i = 0; i < numOutput; ++i) {
            for (int j = 0; j < numHidden; ++j) {
                output[i] += hidden[j] * weightHO[i][j];
            }
        }
        output = tambahbias(output);
        output = activate(output);
        std::vector<double> errorO(numOutput);
        errorO = hitungError(output, target);
        std::vector<double> gradO(numOutput);
        gradO = derivation(output);
        for (int i = 0; i < numOutput; ++i) {
            gradO[i] = gradO[i] * errorO[i] * 0.1;
        }
        for (int i = 0; i < numOutput; ++i) {
            for (int j = 0; j < numHidden; ++j) {
                weightHO[i][j] += (gradO[i] * hidden[j]);
            }
        }
        std::vector<double> gradH(numHidden);
        std::vector<double> derH(numHidden);
        derH = derivation(hidden);
        for (int i = 0; i < numHidden; ++i) {
            for (int j = 0; j < numOutput; ++j) {
                gradH[i] = gradO[j] * weightHO[j][i];
            }
            gradH[i] = gradH[i] * derH[i] * 0.1;
        }
        for (int i = 0; i < numHidden; ++i) {
            for (int j = 0; j < numInput; ++j) {
                weightIH[i][j] += (gradH[i] * a[j]);
            }
        }


    }

Answer №1

Instead of repeatedly copying your std::vectors into functions:

void NeuralNetwork::train(std::vector<double> a, std::vector<double> target) 

consider using references instead:

void NeuralNetwork::train(const std::vector<double>& a, const std::vector<double>& target)

Copying a vector incurs an O(n) operation in both space and time, while using a reference is O(1) in both aspects.

A const std::vector reference is unchangeable; therefore, if you are copying the vector before and after modification:

std::vector<double> NeuralNetwork::derivation(std::vector<double> a)

prefer using a non-const reference instead:

void NeuralNetwork::derivation(std::vector<double>& a)

Answer №2

After some reflection, it appears that my lack of knowledge about debug versus release versions led me to overlook the solution. Making this program a release version resolved the issue. Thank you to everyone for your valuable assistance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What methods are available for parsing JSON data into an array using JavaScript?

I possess an item. [Object { id=8, question="وصلت المنافذ الجمركية في...طنة حتّى عام 1970م إلى ", choice1="20 منفذًا", more...}, Object { id=22, question="تأسست مطبعة مزون التي تع... الأ ...

Quiz application features various button states for optimal user interaction

I am in the process of creating a quiz that resembles the popular BuzzFeed quizzes such as THIS ONE. Although I have mapped out the logic and have an idea of how to code it to function similarly to the one provided in the link, I am encountering issues wit ...

Utilizing jQuery AJAX to transfer files from the client side in .NET platform

I need to upload files from the client side using a jQuery Ajax function to a location on a different server, rather than sending them to my application's web server. This is to prevent unauthorized or virus-infected uploads to the application web ser ...

How can I execute a function when ng-click is triggered on an <a> tag, and ensure it opens in a new tab?

I am facing an issue with an element in my code, which is as follows: <a ng-click="vm.openPage(page)">{{page.pageId}}</a> Within the vm.openPage() function, there are validations that need to be performed before redirecting to the page refere ...

JS - what could be causing this to not work properly? Could there be a bug that

Can anyone help me troubleshoot this code? It is supposed to add a search parameter page=value to the URL and load the page, but it's not working. I'm not sure if there's a typo in there. $(function(){ $('.page').on('cl ...

Firefox failing to trigger key events within iframe

For fun, I created my own little JSFiddle website where I built a Snake implementation that works great in Chrome. However, when I try to use it in Firefox, I can't control the player with the arrow keys or WASD. You can check it out here: I read on ...

Troubleshooting: ng-disabled feature is not properly functioning with Bootstrap buttons

I am currently using a combination of bootstrap.js and angular js in my project. The code snippet I have is as follows: //snippet from the controller $scope.isWaiting = true; $scope.promise = $http.get("voluumHandler.php?q=campaigns&filter=traffic-sou ...

Detecting and removing any duplicate entries in an array, then continually updating and storing the modified array in localstorage using JavaScript

I'm facing an issue with the function I have for pushing data into an array and saving it in local storage. The problem is that the function adds the data to the array/local storage even if the same profileID already exists. I want a solution that che ...

Tips for uploading a jpg image to the server using react-camera

My objective is to transfer an image captured from a webcam to a Lambda function, which will then upload it to AWS S3. The Lambda function appears to work during testing, but I'm struggling to determine the exact data that needs to be passed from the ...

What is the process of passing a JavaScript variable to PHP with AJAX?

In the given scenario, I have an HTML file that is intended to display the content of a text file at div id="myDiv". The text file content will be read by PHP. However, there seems to be an issue in retrieving the content from the text file. I need assis ...

Creating Vue3 Component Instances Dynamically with a Button Click

Working with Vue2 was a breeze: <template> <button :class="type"><slot /></button> </template> <script> export default { name: 'Button', props: [ 'type' ], } </scr ...

Having trouble getting the .each() method to function properly in jQuery

Looking for a solution to a similar issue here. Currently, I am attempting to iterate through multiple forms on a webpage and perform various actions with those forms. However, I am facing some challenges in making it work. Below is the code I am using: ...

Steps to Incorporate jQuery Function in a Partial View Inside a Modal

My jquery button click method is functioning correctly in views outside of modals, but the uploadbtn button click method does not work when a partial view is loaded in the modals. <script src="~/lib/jquery/dist/jquery.min.js"></script> ...

Retrieving the value of an ASP.NET Literal in JavaScript

Is there a way to retrieve the value of an ASP.NET Literal control in JavaScript? I attempted the code below but it didn't return any values: var companyName = document.getElementById('litCompanyName').textContent; var companyNumber = docum ...

There are no values in the request.query object in express.js

I am facing an issue with the redirect URL I received from Google OAuth2: http://localhost:997/?#state=pass-through%20value&access_token=ya29.ImC6B1g9LYsf5siso8n_UphOFB0SXc5dqsm6LqHRWXbtNHisEblxjeLoYtGgwSVtCTGxOjjODiuTyH7VCHoZCEfUd_&token_type=Bea ...

Using Formik with MUI Multiple Select

Exploring the world of MUI and Formik, I encountered a challenge with creating a multiple Select in my form. It's my first time working with these tools, so I have a question regarding the implementation. Here's what I've tried based on the ...

Launching an external software using electron

I am in the process of developing my own personalized Electron app for managing other applications on my device. One issue I have encountered is the inability to create a link that opens my own .exe applications. I have attempted various methods without su ...

Guide on notifying the client when the database is updated, similar to the notification system used in Facebook chat

Is it possible to send an alert to the client using the website only when a specific field is updated? I understand how to periodically check for database updates with silent Ajax calls, but I am looking to trigger an Ajax call only when relevant informa ...

What is the best way to retrieve a value in Ajax?

I'm trying to assign the result of an MVC controller method to a variable. function someFunction(){ var result; $.Ajax{ //??? } return result; } //Contrast with C++ int f() { //just! return result; } Post Script: Th ...

What is the best way to utilize JSONP to display an entire HTML code with an alert?

When I attempt to use cross-domain ajax to retrieve the entire HTML page code, I keep receiving a failed message. The console log shows: "Uncaught SyntaxError: Unexpected token <" Below is my AJAX function: function fetchData(){ var url = documen ...