Does migrating code from vb.net to a C++ dll offer significant performance boosts?
I know simular questions have been asked before but I believe my specifics vary enough that this cam be it's own question. If I've missed another question that's very simular please link it for me.
I'm proficient in vb.net but a total novice at c++. I've got a subroutine in vb.net that just does a lot of maths. There's some trigonometry and squareroots etc. nothing too demanding but it's around 100 equations and they have to be run thousands of times.
Here's some pseudo code of what I do:
Sub mathsub()
For i = 0 to arraylength
A = somenum(i) * othernum(i)
...
Next
End sub
So I do all the math inside the for loop many thousands of times. Each time uses a different element of a bunch of arrays (somenum, othernum, etc.), all of these arrays are the same length.
No single line of code takes any significant length of time (when profiled each line takes a negligible length of time), but all in all the program takes longer than I'd like. Can I expect a significant speed increase by rewriting this routeen in c++ and referencing it from vb.net?
Edit #1 - answers to questions in comments
The code takes a negligible amount of time per array element but there's about 20,000 elements and I need to do this about 10,000 times (so 200 million times - no joke). All in I've estimated it taking around 18 hours based on how long it takes for a fraction of the work. The entire program will need to be run multiple times as well, although each new run is 100% separate an unrelated. I have tried threading the code, I have a Ryzen 1800x 8 core (16 thread) processor - I've tried splitting the task into exactly 15 thread (leaving 1 thread for overhead and other activities) and using a parallel.for loop and both don't offer enough of an increase yet. I don't know what AVX is, but I'll start looking into it, I've never written a line of C++, but the maths itself is all just simple equations and I'm happy to spend a few days/weeks/months learning implementing if it's seriously going to make a difference!
1 answer
-
answered 2018-11-08 07:24
nunya
Benchmark it. There's no way to know that without benchmarking, but the answer is likely to be "yes" because of C++'s performance profile versus a managed language like VB.NET, but JIT optimizations, managed-to-native transitions, array access order / data locality, and general coding technique can all have an impact here.
See also questions close to this topic
-
omp parallel for - loop execution stuck after 1/6 of iterations have been done (with 6 threads)
I'm having problems parallelizing my code. I'm using C++/CLI with windows forms in VS2017. I was used to just write my parallel loops with concurrency parallel_for but crt is not supoported with /clr, which forces me to use OpenMP. I am a beginner with omp and the research I made didn't give me a solution to my problem. My code runs completely fine without the "#pragma omp parallel for" line. I only want to parallelize the inner loop, because that's where the most computationally expensive part is. Inside the inner loop, I am using some variables from outside both loops, but I only read them, I do not change them. All the other variables are declared inside the inner loop, which should not cause any problems. My code runs untill some time and then just freezes, not computing anything (according to my task manager).
I played around with the loop ranges and found out, that when I change the parallel for loop range, the freeze occurs at a different iteration - I eventually figured it's always at 1/6 of the loop range (my CPU has 6 single-threaded cores). Only one core seems to be computing only 1/6 of the loop. I tried to run some other code with the same "#pragma omp parallel for" syntax to check if my compiler or project settings are right, and with the simple test code, I am really getting 100% utilization, roghly 6x speedup. Any ideas, what might be wrong?
for (int mimosloupeciter = 0; mimosloupeciter < iters_horizontal; mimosloupeciter++)//X cyklus { double beta = asin(abs((double)mimosloupeciter - floor((double)iters_horizontal / 2)) / R); #pragma omp parallel for for (int meridianiter = 0; meridianiter < iters_vertical; meridianiter++)//Y cyklus { //some expensive computation } }
-
Is there is a difference in time and space complexicity between equalization sign and initialisation?
For example i have the following code:
int value = 10; int firstMethod = value; int secondMethod (value);
What is the difference in time and space if I use second method? Is it gonna take longer? Is there any reason why people write code with first method?
-
AWS lambda C++ runtime in SAM
Does anyone have a step-by-step tutorial on using SAM to package an AWS lambda function using the C++ runtime so I can run it locally? C++ is not one of the languages supported using
sam init --runtime
and I cannot work out the steps needed to package the Hello World function from https://aws.amazon.com/blogs/compute/introducing-the-c-lambda-runtime/ -
Referencing debug dlls while build Release version
I am trying to build a release version of my vb.net project. My project references multiple dlls(I have both release and debug versions of these dlls). When I build my project, I set my configuration to Release (obviously), but do I also need to reference my release dlls or is referencing my debug dlls the same? I am simply curious to know if this makes any difference or not.
-
Need Excel macro
I need code to erase a range in excel from a starting cell to the end, and the end can change with each use, and to copy a formula from a cell down a number of times that is located in a named cell.
-
PostBack shfits Radwindow on page_load from dynamically created RadWindow
I am dynamically creating a RadWindow, and so after it is created there is a button in that RadWindow. Also has a checkbox that does a post back. After i click button the Radwindow does some saving. but after the post back and the reload My radwindow shifts slightly to the right?
Parent Page
Private Sub btnAddSupervision_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddSupervision.Click getWindow("Add", False) End Sub Private Sub getWindow(Title As String, IncludeSupervision As Boolean) Dim PageUrl As String = "~/Supervision_Edit.aspx" Menuradwindow.Windows.Clear() Menuradwindow.VisibleOnPageLoad = False Dim newWindow As New RadWindow() newWindow.AutoSize = True newWindow.VisibleOnPageLoad = True newWindow.Modal = False newWindow.MaxWidth = 800 Menuradwindow.Windows.Add(newWindow) newWindow.DestroyOnClose = True newWindow.BorderWidth = 1 newWindow.Behaviors = WindowBehaviors.Default newWindow.BorderStyle = BorderStyle.None newWindow.VisibleStatusbar = False newWindow.Title = Title newWindow.NavigateUrl = PageUrl & "?SupervisionID=" & SupervisionID & "&StaffRosterID=" & StaffRosterID & "&ButtonID=" & Title End Sub
ChildRadWindow Page
Private Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init ModalButton1.Visible = False ModalButton2.Visible = False ModalButton3.Visible = False ModalButton4.Visible = False ModalButton5.Visible = False ButtonTextID = (Request.QueryString("ButtonID")).ToString If Not ButtonTextID = _Add Then currSupervisionID = (Request.QueryString("SupervisionID")) currStaffRosterID = (Request.QueryString("StaffRosterID")) End If 'view data, to create dynamic controls If ButtonTextID = _Add Then PopulateCheckBox("[spGet_Supervision_SupervisedStaff]") BuildQuestionControl(pnlQuestionsForSupervisor, "[spGet_Supervision_QuestionsForSupervisor]") pnlQuestionsForStaff.Visible = False ElseIf ButtonTextID = _Acknowledge Then BuildQuestionControl(pnlQuestionsForSupervisor, "[spFill_Supervision_ViewQuestionsForSupervisior]", "@SupervisionID", currSupervisionID, "@StaffRosterID", currStaffRosterID) pnlQuestionsForSupervisor.Enabled = False BuildQuestionControl(pnlQuestionsForStaff, "[spGet_Supervision_QuestionsForStaff]", "@SupervisionID", currSupervisionID, "@StaffRosterID", currStaffRosterID) dtpSupervisionDate.Enabled = False ElseIf ButtonTextID = _View Then BuildQuestionControl(pnlQuestionsForSupervisor, "[spFill_Supervision_ViewQuestionsForSupervisior]", "@SupervisionID", currSupervisionID, "@StaffRosterID", currStaffRosterID) pnlQuestionsForSupervisor.Enabled = False BuildQuestionControl(pnlQuestionsForStaff, "[spFill_Supervision_ViewQuestionsForStaff]", "@SupervisionID", currSupervisionID, "@StaffRosterID", currStaffRosterID) pnlQuestionsForStaff.Enabled = False btnSubmit.Visible = False dtpSupervisionDate.Enabled = False End If End Sub Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click Page.Validate() If Page.IsValid Then If ButtonTextID = _Add Then ' SaveSupervision() ' SaveSupervisionStaff() ElseIf ButtonTextID = _Acknowledge AndAlso Not chkNoComment.checked = True Then ' SaveAcknowledgeQuestions() End If ScriptManager.RegisterStartupScript(Page, Me.GetType, "refreshParent", "refreshParent(); ", True) Else ScriptManager.RegisterStartupScript(Me, Me.GetType, "Error", "alert('Please make sure all fields are filled.');", True) End If End Sub
-
Efficiently compute distances between thousands of coordinate pairs
I have a catalog I opened in python, which has about 70,000 rows of data (ra, dec coordinates and object name) for various objects. I also have another list of about 15,000 objects of interest, which also appear in the previously mentioned catalog. For each of these 15,000 objects, I would like to see if any other objects in the large 70,000 list have ra, dec coordinates within 10 arcseconds of the object. If this is found to be true, I'd just like to flag the object and move on to the next one. However, this process takes a long time, since the distances are computed between the current object of interest (out of 15,000) 70,000 different times. This would take days! How could I accomplish the same task more efficiently? Below is my current code, where
all_objects
is a list of all the 15,000 object names of interest andcatalog
is the previously mentioned table data for 70,000 objects.from astropy.coordinates import SkyCoord from astropy import units as u for obj_name in all_objects: obj_ind = list(catalog['NAME']).index(obj_name) c1 = SkyCoord(ra=catalog['RA'][obj_ind]*u.deg, dec=catalog['DEC'][obj_ind]*u.deg, frame='fk5') for i in range(len(catalog['NAME'])): if i != obj_ind: # Compute distance between object and other source c2 = SkyCoord(ra=catalog['RA'][i]*u.deg, dec=catalog['DEC'][i]*u.deg, frame='fk5') sep = c1.separation(c2) contamination_flag = False if sep.arcsecond <= 10: contamination_flag = True print('CONTAMINATION FOUND') break
-
Is there a faster way to compute element wise exponentials of a matrix in Matlab?
I am profiling my code and this one line seems to be a bottleneck. The idea is to create a spatial correlation matrix of n observations of a given dimension, based upon a theta vector of the same dimension--which contains dimensional hyperparameters to be fit.
In my overall code this spatial correlation function is called thousands of times (per iteration) while computing a likelihood function in order to optimize my theta parameters. The number of observations grows by one in each iteration of the overall code, and the theta parameters must be refit each iteration. So you can see how this line of code becomes crucial as the algorithm progresses.
I think that the slowest line, i.e.,
R = exp(sum(bsxfun(@times, -abs(D_X).^corr_model,reshape(theta,[1 1 d])),3));
takes the most time to compute the final element-wise exponential across the resulting n by n matrix (the n by n matrix is yielded after summing over the 3 dimension of the distance matrix). But there is a lot going on in this line, so I am unsure if this is the most critical aspect to the overall performance.Thanks for any insight you may have!
I have already replaced a
repmat
command with absxfun
, to multiply the given thetas across the dimensional distance matrixD_X
, which sped up the code notably. However, nesting a secondbsxfun
to execute the squaring of distances i.e., to replaceabs(D_X).^corr_model
, made the code run slower.n = 500; dimension = 20; D_X = repmat(rand(n),[1 1 dimension]); theta = rand(dimension, 1); corr_model = 2; R = corr(corr_model,theta, D_X); function R = corr(corr_model,theta,D_X) % calculate the correlation matrix for the modified nugget effect model % corr_model - the correlation model used for the spatial correlation % corr_model = 2: gaussian correlation function % theta - vector of hyperparameters % D_X - the distance matrix for the input locations d = size(theta,1); switch corr_model case 2 %Gaussian correlation function R = exp(sum(bsxfun(@times, -abs(D_X).^corr_model,reshape(theta,[1 1 d])),3)); end end
-
How to make images load fast
Need to learn the steps a website coder needs to do to create fast loading images.
I’m a netrepreneur, not a website coder just so you know.
So I had posted in a FB group about something & came to learn from a web developer that the way you load images fast is to make sure they fit the SIZE of the container.
I’d never heard of this before & 100% of the website coders I’ve been screening for a job I need done don’t even mention this when I ask. :frowning:
One of my screening questions is... "How do you create fast loading images?"
If the odd one says "resize" the image, NO ONE says anything about the container.
Should tell tell me they don't know what they are doing?
And other than the sizing of the images properly, do they also have to optimize the images?
And do I still need to put my images on a CDN so if they don't mention a CDN, I know they don't know what they are doing?
For my own understanding, do I really need a CDN to make my site load faster?
I don’t have a lot of images, just the ones that are on the index page & one image within every article in the blog area.
Thanks
-
Is it possible that a .jar file called from c++ writes a file?
I am trying to get the output of a .jar file from my C++ used in UWP. The jar contains a complex algorithm and writes the output to a file. Calling it through the console works perfect but inside my program it seems to execute but not creating a file.
Don't ask now why I'm desperating getting the output via a file instead of Pipes. This is also a question from me: CreateProcess Pipe is always empty
It actually returns 1 so it tells me that it doesn't find the file.
This is how I try to implement my .jar in my C++ dll:
STARTUPINFO sInfo; ZeroMemory(&sInfo, sizeof(sInfo)); PROCESS_INFORMATION pInfo; ZeroMemory(&pInfo, sizeof(pInfo)); sInfo.cb = sizeof(sInfo); //if (!SetHandleInformation(wPipe, HANDLE_FLAG_INHERIT, 0)) //return "Error SetHandleInformation"; if (!CreateProcess(TEXT("C:\\\\Program Files (x86)\\Java\\jdk1.8.0_161\\jre\\bin\\java.exe"), TEXT("-jar decode_fileout.jar"), NULL, NULL, false, CREATE_DEFAULT_ERROR_MODE, NULL, NULL, &sInfo, &pInfo)) { return 0; } WaitForSingleObject(pInfo.hProcess, INFINITE); string fileContent; ifstream myfile("decode.txt"); if (myfile.is_open()) { getline(myfile, fileContent); myfile.close(); } else return 1; char *endPtr; if (isdigit(fileContent[0])) return strtoll(fileContent.c_str(), &endPtr, 10); else return 2;
-
How to test my dll file written in fortran?
I have written a Fortran code for being compiled as a '*.DLL' file.
The program which reads that file is a Finite Elements Method software named Plaxis, I already achieved to generate the '*.DLL' file in Visual Studio and Plaxis recognizes my model but the model does not work fine.
I would like to evaluate all the variables involved in my code and the procedure that Plaxis is using to read them, but when I use commands like "write(*,*) 'variable'" Plaxis does not show me what I asked in the source code.
-
Cleanest method to include all required DLLs in a single nuget package?
I am trying to create a nuget package of a binary PowerShell module that wraps another C# Main Library project. I am struggling to get all the required DLLs included in the generated nuget package because the Main Library has lots of nuget package dependencies that aren't being included.
The reason why I want the nuget package to include both the two projects DLL files but also Main Library's required DLL files is so that I can create a psd1 file for the binary PowerShell module that will have all the required DLLs under the
RequiredAssemblies
field. This is required as all the required DLLs must be imported before importing the main binary PowerShell module DLL file.Below is the package structure I am looking for:
Package - lib - netstandard2.0 - PowerShellModule.dll - PowerShellModule.psd1 - MainLibrary.dll - MainLibraryDep1.dll - MainLibraryDep2.dll - ...
Once the nuget package has been installed I should be able to call
Import-Module "Package\lib\netstandard2.0\PowerShellModule.psd1"
and be good to go.When using
nuget pack -IncludeProjectReferences
in the binary PowerShell module project folder it successfully includes the binary PowerShell module DLL and the Main Library DLL in the final package but none of the nuget dependencies that the Main Library has. Is there any way to include these?One solution I thought of was simply building the PowerShell binary module and making sure it generated all the required DLLs (including those for Main Library), copying these files to a folder and packaging that folder however that seems very hacky and not something I would really want to do.
I'm also aware that I should really just have the binary PowerShell module project build as a separate nuget package that is dependent on the Main Library which in turn has all its dependenices, however this would mean after installing all the packages each of the RequiredAssemblies fields in the psd1 file would have to jump out of the current directory a few times using
..\..\
so that it could get into one of the other depdendent packages to import their dll file. This is due to the way nuget installs it's packages and as far as I'm aware you cannot change this.