logo
down
shadow

Array of structs with dynamic allocation runs very slow in C in comparison to Python


Array of structs with dynamic allocation runs very slow in C in comparison to Python

By : atosh
Date : October 18 2020, 06:10 PM
fixed the issue. Will look into that further Your "hash" in C operates more like a linked list, with linear insertion and lookup. On the other hand, Python's dictionary is industrial-strength with O(1) average insertions and lookups (the in operator). If you're writing a hashmap from scratch in C, there's a good deal of theory you're going to need to put into practice in order to begin approaching Python's implementation in terms of performance.
In my opinion, the best bet is to write your code in C++ if possible and use an unordered_map. This is the best of both worlds: all the work has already been done for you, yet you don't need to make performance compromises.
code :


Share : facebook icon twitter icon
Dynamic allocation of an array of structs

Dynamic allocation of an array of structs


By : New Home in Turkey
Date : March 29 2020, 07:55 AM
it should still fix some issue I've found useful answers on other people's questions countless times here on stackoverflow, but this is my first time asking a question of my own. , The error is here:
code :
for (i = 0; i < *count; i++) {
    data[i]->a = i;
    data[i]->b = i * 2;
    printf("%d.a: %d\n", i, data[i]->a);
    printf("%d.b: %d\n", i, data[i]->b);
}
for (i = 0; i < *count; i++) {
    (*data)[i].a = i;
    (*data)[i].b = i * 2;
    printf("%d.a: %d\n", i, (*data)[i].a);
    printf("%d.b: %d\n", i, (*data)[i].b);
}
Memory allocation on GPU for dynamic array of structs

Memory allocation on GPU for dynamic array of structs


By : MVCPro
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I have problem with passing array of struct to gpu kernel. I based on this topic - cudaMemcpy segmentation fault and I wrote sth like this: ,
This is allocating a new pointer to host memory:
code :
test[i].array = (char*)malloc(size * sizeof(char));
memcpy(test[i].array, temp, size * sizeof(char));
cudaMalloc((void**)&(test[i].array), size * sizeof(char));
$ cat t755.cu
#include <stdio.h>
#include <stdlib.h>

struct Test {
    char *array;
};

__global__ void kernel(Test *dev_test) {
    for(int i=0; i < 5; i++) {
        printf("Kernel[0][i]: %c \n", dev_test[0].array[i]);
    }
}

int main(void) {

    int n = 4, size = 5;
    Test *dev_test, *test;

    test = (Test*)malloc(sizeof(Test)*n);
    for(int i = 0; i < n; i++)
        test[i].array = (char*)malloc(size * sizeof(char));

    for(int i=0; i < n; i++) {
        char temp[] = { 'a', 'b', 'c', 'd' , 'e' };
        memcpy(test[i].array, temp, size * sizeof(char));
    }

    cudaMalloc((void**)&dev_test, n * sizeof(Test));
    cudaMemcpy(dev_test, test, n * sizeof(Test), cudaMemcpyHostToDevice);

    // Step 3:
    char *temp_data[n];
    // Step 4:
    for (int i=0; i < n; i++)
      cudaMalloc(&(temp_data[i]), size*sizeof(char));
    // Step 5:
    for (int i=0; i < n; i++)
      cudaMemcpy(&(dev_test[i].array), &(temp_data[i]), sizeof(char *), cudaMemcpyHostToDevice);
    // now copy the embedded data:
    for (int i=0; i < n; i++)
      cudaMemcpy(temp_data[i], test[i].array, size*sizeof(char), cudaMemcpyHostToDevice);

    kernel<<<1, 1>>>(dev_test);
    cudaDeviceSynchronize();

    //  memory free
    return 0;
}

$ nvcc -o t755 t755.cu
$ cuda-memcheck ./t755
========= CUDA-MEMCHECK
Kernel[0][i]: a
Kernel[0][i]: b
Kernel[0][i]: c
Kernel[0][i]: d
Kernel[0][i]: e
========= ERROR SUMMARY: 0 errors
$
struct Test {
    char array[5];
};
$ cat t755.cu
#include <stdio.h>
#include <stdlib.h>

struct Test {
    char array[5];
};

__global__ void kernel(Test *dev_test) {
    for(int i=0; i < 5; i++) {
        printf("Kernel[0][i]: %c \n", dev_test[0].array[i]);
    }
}

int main(void) {

    int n = 4, size = 5;
    Test *dev_test, *test;

    test = (Test*)malloc(sizeof(Test)*n);

    for(int i=0; i < n; i++) {
        char temp[] = { 'a', 'b', 'c', 'd' , 'e' };
        memcpy(test[i].array, temp, size * sizeof(char));
    }

    cudaMalloc((void**)&dev_test, n * sizeof(Test));
    cudaMemcpy(dev_test, test, n * sizeof(Test), cudaMemcpyHostToDevice);

    kernel<<<1, 1>>>(dev_test);
    cudaDeviceSynchronize();

    //  memory free
    return 0;
}
$ nvcc -o t755 t755.cu
$ cuda-memcheck ./t755
========= CUDA-MEMCHECK
Kernel[0][i]: a
Kernel[0][i]: b
Kernel[0][i]: c
Kernel[0][i]: d
Kernel[0][i]: e
========= ERROR SUMMARY: 0 errors
$
regarding dynamic allocation array of a structs and sending it between functions

regarding dynamic allocation array of a structs and sending it between functions


By : ARIJIT ADGIRI
Date : March 29 2020, 07:55 AM
should help you out i have a few issues with that i was wondering what am i doing wrong and if can someone explain me futher details about the realloc and malloc functions. the problem i have is from my main: , In addbook
code :
void addbook(book* books){
    ..
    libsize*=1.5;}
    temp=(book*)realloc(books,libsize);
    }
temp = realloc(books,libsize*sizeof(book));
Dynamic Memory Allocation for array of structs

Dynamic Memory Allocation for array of structs


By : nreich
Date : March 29 2020, 07:55 AM
it should still fix some issue Though I'm not sure, for I have no idea how you call these from your main nor the content of the assignment; I suspect that you need change the following line;
code :
driver->races = (Race *)malloc(sizeof(Race));
driver->races = (Race *)malloc(noRaces * sizeof(Race));
Dynamic allocation of an array of structs does not work

Dynamic allocation of an array of structs does not work


By : antik486
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Sorry, but I added some print statements in your code while running at my end.
I did the below to get rid of the '\n' left in the buffer after scanf; and it yielded me good result. That's what is the root of the issue, I reckon. Unclean buffer.
code :
int c;
while ((c=getchar()) != '\n' && c != EOF);

#include <stdlib.h>
#include <string.h>

int main()
{
    struct DEP
    {
        char name[30];
        char rank;
        int number;

    };
    struct DEP *members;
    int size, i, c;

    scanf("%d", &size);
    members = malloc(size * sizeof(struct DEP));
    if(members == NULL)
    {
        return 1;
    }

    while ((c = getchar()) != '\n' && c != EOF);
    for(i = 0;i < size;i++)
    {
        printf ("Enter Name: \n");
        fgets(members[i].name, 30, stdin);
        members[i].name[strcspn(members[i].name, "\n")] = '\0';
        printf ("Enter rank and number: ");
        scanf("%c %d", &members[i].rank, &members[i].number);
        while ((c = getchar()) != '\n' && c != EOF);
        printf("Name: %s\nRank: %c\nNum: %d\n", members[i].name, members[i].rank, members[i].number);
    }


    return 0;
}
$ ./main.out
3
Enter Name:
siddharth
Enter rank and number: z 5
Name: siddharth
Rank: z
Num: 5
Enter Name:
sid
Enter rank and number: s 6
Name: sid
Rank: s
Num: 6
Enter Name:
sidhh
Enter rank and number: e 8
Name: sidhh
Rank: e
Num: 8
Related Posts Related Posts :
  • Unit Test Won't Run Tests
  • Use two for loops simultaneously
  • can we display glass bar chart in python with google app engine
  • Scapy install issues. Nothing seems to actually be installed?
  • Why do people write the #!/usr/bin/env python shebang on the first line of a Python script?
  • What does s() mean?
  • ROC AUC value is 0
  • Why is this the value?
  • Best practices for logging in django project
  • Is there a python openid apps-discovery library to get appengine apps onto the apps marketplace
  • Cannot fetch a web site with python urllib.urlopen() or any web browser other than Shiretoko
  • Similar to ``tabnanny``, how can I check that all the python code is using 4 spaces as an indent?
  • Python: object identity question?
  • Multiple For loops, print else only once if condition is not met
  • Select one item from Series and keep the index
  • __repr__ method appears can't be invoked automatically for Exception class
  • Problem with list value (ValueError) in python 3
  • How to get TouchSensor nested under joint in Webots (Python API)
  • How to specify kernel while executing a Jupyter notebook using Papermill's Python client?
  • How to hide password in Database Connection?
  • How to get a list of dictionaries from the following code?
  • 'How to find out noun to which pronoun is referring to' in python
  • Removing a character (^) from each row of panda Dataframe and get unique words in each row
  • Changing a static variable of inherited classes
  • Django Query result comparison with if statement
  • Python: how to merge two dataframe based only on different columns?
  • Filter data by last 3 months and by ID
  • Inplace arithmetic operation versus normal arithmetic operation in PyTorch Tensors
  • How can I add custom signs to spaCy's punctuation functionality?
  • Ensure positive difference of two numbers
  • i keep getting an error that my list index is out of range
  • Is there a way to create gantt charts in python?
  • How to view network weights and bias during training
  • How can I force SAS to wait for a command to fully execute?
  • Remove all occurences of a value from a nested dictionary
  • How to ensure secure randomization for python password generator
  • Amazon SageMaker deploying from model artifacts - what object do we load from archive?
  • [] parameter or input used in sum() function - what is it doing?
  • Outlook email text formatting from Python application
  • Python 3 - comparing enums against hex value
  • Elegant way to check if a float is between two numbers in Python?
  • Understanding return [0,size-1][nums[0]<nums[size-1]] in Python
  • How do I make this script that heats up my CPU safe
  • RegEx for matching capital letters and numbers
  • What is differnces between array[0] and array[0:1] in Python?
  • How to run both items in scrapy function?
  • How to count the number of sequences of n numbers where no two adjacent numbers are the same?
  • Is there a more efficient way to re-write multi if-else statement
  • ValueError: Error when checking target: expected dense_3 to have shape (1000,) but got array with shape (1,)
  • SytanxError: Invalid Sytax
  • Setting debug = False makes the Django app crash with the following error, how to fix it?
  • How to get the average of many lists embedded within each other?
  • Paramiko with subprocess
  • 2D table conversion for example: y = f(x1,x2) => x1 = f(y, x2)
  • Return a literal string of a tuple in python
  • How to split a Column when you have same values?
  • How to perform str.strip in dataframe and save it with inplace=true?
  • why zip(*k) can't work when k is a iterator?
  • How to get list as an input from command line python?
  • Is Tensorflow Dataset.from_generator deprecated in tensorflow 2.0 ? It throws tf.py_func deprecation error
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk