IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

Programme qui consomme 100% CPU,des astuces pour optimiser les ressources processeur?


Sujet :

C#

  1. #1
    Membre du Club
    Profil pro
    Étudiant
    Inscrit en
    Novembre 2004
    Messages
    54
    Détails du profil
    Informations personnelles :
    Âge : 34
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Novembre 2004
    Messages : 54
    Points : 49
    Points
    49
    Par défaut Programme qui consomme 100% CPU,des astuces pour optimiser les ressources processeur?
    Bonjour,
    j'avais chosit le C# pour réaliser mon application de serveur-proxy suite à comparatif de vitesse qui le montrait bien placé pour les threads.
    Après une ébauche du projet (200 lignes), je m'apperçois que mon programme utilise 50% du processeur avec un client connecté, 100% avec 2 clients.


    Pourtant, le serveur (écrit en C++) sur lequel est connecté le proxy utilise peu de ressources processeur, alors qu'il analyse autant de données que le proxy !

    Je me demande alors comment trouver les instruction qui consomment beaucoup de ressources processeur ?
    variables globales ? manipulations de tableaux excessive sachant que le programme reçoit des données tous les dizièmes de secondes ?


    Voici le code source de mon projet.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Collections;
    using System.Threading;
    using System.IO;
    using YSPS_apps;
     
    namespace YSPS_apps
    {
        //global variables
        public static class Common 
        {
            public static ArrayList acceptList = new ArrayList(); // liste to access the sockets variables of all the clients
            public static ArrayList usernameList = new ArrayList(); // list of the usernames
        }
     
     
        public class Client
        {
            public Socket socketServer;
            public Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            public string username;
            public int version;
     
            private static Int32 bytesToInt32(byte[] FourByteArrToConvert)
            {// convert a byte to an integer
                return System.BitConverter.ToInt32(FourByteArrToConvert, 0);
            }
            private static byte[] int32ToBytes(Int32 int32Input)
            {// convert an integer to a byte
                byte[] numBytesBuf = new byte[4];
                return System.BitConverter.GetBytes(int32Input);
            }
            private static byte[] byte_concat(byte[] array1, byte[] array2)
            {
                byte[] array3 = new byte[array1.Length + array2.Length];
                array1.CopyTo(array3, 0);
                array2.CopyTo(array3, array1.Length);
                return array3;
            }
     
            public Client(System.Net.Sockets.Socket CurrentClient2)
            {
                socketServer = CurrentClient2;
                IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7914);
                socketClient.Connect(ipEnd);// YSPS connects to the server
                Console.Out.WriteLine(socketClient.Available + "et" + socketServer.Available);//debug output
                while (socketServer.Available == 0)
                {
                    Console.Out.WriteLine("sleep");//debug output
                    Thread.Sleep(200);//wait an expect an answer from the YSFS server
                    if (socketServer.Available != 0)
                        break;
                }
                byte[] msgFromServer = new Byte[socketServer.Available];
                socketServer.Receive(msgFromServer, 0, socketServer.Available, SocketFlags.None);
                //Console.Out.WriteLine("valeur" + System.Text.Encoding.UTF8.GetString(msgFromServer).Trim().IndexOf('\x0018') + System.Text.Encoding.UTF8.GetString(msgFromServer).Trim().IndexOf('\x0061') + System.Text.Encoding.UTF8.GetString(msgFromServer).Trim().IndexOf('\x007A') + System.Text.Encoding.UTF8.GetString(msgFromServer).Trim().IndexOf('\x0065'));
                byte[] user=new byte[16];
                for (int i = 0; i < 16; i++)
                {
                    user[i] = 32;
                }
                for (int i = 8; i < 16;i++)
                {
                    if (msgFromServer[i] == 0)
                    {
                        break;
                    }
                    user[i-8]=msgFromServer[i];
                }
     
                username = System.Text.Encoding.UTF8.GetString(user);
                username=username.Normalize().Trim();
                Console.Out.WriteLine(username.Length);
                Console.Out.WriteLine("username " + username+ "end");
                Common.usernameList.Add(username);
                socketClient.Send(msgFromServer);
            }
            public void run()
            {
                while (true)
                {
                    if (socketClient.Available > 0)
                    {//from server
                        byte[] msgToClient = new Byte[socketClient.Available];
                        socketClient.Receive(msgToClient);
                        //socketClient.Receive(msgToClient, 0, socketClient.Available, SocketFlags.None);
                        string messageReceived = System.Text.Encoding.UTF8.GetString(msgToClient).Trim();
     
                        try
                        {
                            socketServer.Send(msgToClient);
                        }
                        catch
                        {
                            Console.Out.WriteLine(username + " has left the server");
                            break;
                        }
                    }
                    if (socketServer.Available > 0)
                    {//from client
                        byte[] msgLength = new Byte[4];
                        socketServer.Receive(msgLength, 0, 4, SocketFlags.None);
                        int byte_length = bytesToInt32(msgLength);
                        if (byte_length <= socketServer.Available)
                        {//if the message-length match with the real length of the packet
                            byte[] msgToServer = new Byte[byte_length];
                            socketServer.Receive(msgToServer, 0, byte_length, SocketFlags.None);
     
                            int data_kind = bytesToInt32(msgToServer);
                            //Console.Out.WriteLine(data_kind.ToString());//debug
                            if (data_kind == 32)
                            {//if it's a chat message
                                Console.Out.WriteLine("chat message");
                                string message = System.Text.Encoding.UTF8.GetString(msgToServer).ToString().Trim();//the whole chat message
                                Console.Out.WriteLine(message);//debug
                                int send_to_pos = message.IndexOf("%", username.Length + 2);
                                if (send_to_pos != -1)
                                {//if we found "%"
                                    Console.Out.WriteLine("to an user");
                                    int end_send_to_pos = message.IndexOf('%', send_to_pos + 1);
                                    if (end_send_to_pos != -1)
                                    {
                                        string to_user = message.Substring(send_to_pos + 1, end_send_to_pos - send_to_pos - 1).Trim();
                                        //string chat_message = "[" + username + "] " + message.Substring(end_send_to_pos, message.Length - end_send_to_pos).Trim();
                                        bool to_user_exist = false;
                                        for (int i = 0; i < Common.usernameList.Count; i++)
                                        {
                                            Console.Out.WriteLine("testing " + ((string)Common.usernameList[i]).Trim() + " with " + to_user + " end");
                                            if (((string)Common.usernameList[i]).Trim() == to_user)
                                            {
                                                to_user_exist = true;
                                                Console.Out.WriteLine("User found");
                                                ((Socket)Common.acceptList[i]).Send(byte_concat(msgLength, msgToServer));
                                            }
                                        }
                                        if (to_user_exist == false)
                                        {
                                            Console.Out.WriteLine("Unable to send this message to " + to_user);
                                        }
                                    }
                                    else
                                    {
                                        Console.Out.WriteLine("Failed to find the 2nd %");
                                    }
                                }
                                else
                                {
                                    socketClient.Send(byte_concat(msgLength, msgToServer));//send the chat message to everybody
                                }
                            }
                            else
                            {
                                socketClient.Send(byte_concat(msgLength, msgToServer));//Send to the server
                            }
                        }
     
                    }
                }
            }
     
        }
        public class Server
        {
            public void Start()
            {
                IPHostEntry ipHostEntry = Dns.Resolve(Dns.GetHostName());
                foreach (IPAddress ip in ipHostEntry.AddressList)
                {
                    Console.Out.WriteLine(ip.ToString());
                }
                IPAddress ipAddress = ipHostEntry.AddressList[ipHostEntry.AddressList.Length - 1];
     
                Socket CurrentClient = null;
                Socket ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    ServerSocket.Bind(new IPEndPoint(0, 7915));
                    ServerSocket.Listen(30);
                    while (true)
                    {
                        Console.WriteLine("Attente d'une nouvelle connexion...");
                        CurrentClient = ServerSocket.Accept();
                        Console.Out.WriteLine(CurrentClient.GetType().ToString());
                        Common.acceptList.Add(CurrentClient);
                        Client obj = new Client(CurrentClient);
                        Thread thread2 = new Thread(new ThreadStart(obj.run));
                        thread2.Start();
                        Console.WriteLine("Nouveau client:" + CurrentClient.GetHashCode());
                    }
                }
                catch (SocketException E)
                {
                    Console.WriteLine(E.Message);
                }
            }
        }
     
        class MainClass
        {
            public static void Main(string[] args)
            {
                Server startIt = new Server();
                startIt.Start();
     
            }
     
        }
     
     
    }

  2. #2
    Expert éminent
    Avatar de smyley
    Profil pro
    Inscrit en
    Juin 2003
    Messages
    6 270
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2003
    Messages : 6 270
    Points : 8 344
    Points
    8 344
    Par défaut
    Je pense que ça vient de là :

    Code c# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    while (true)
                {
                    if (socketClient.Available > 0)
                    {
                       ...
                    }
                    if (socketServer.Available > 0)
                    {
                        ...
                    }
                }
    Au final, si il n'y a rien d'Available, ce code est équivalent à
    Code c# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    while(true)
    {
    }
    Donc utilisation max du processeur. Essaye de mettre Thread.Sleep(1) ou Thread.Sleep(100) à la fin de ta boucle.

    ( Par contre, ton titre ne veux pas dire grand chose ... )

  3. #3
    Membre du Club
    Profil pro
    Étudiant
    Inscrit en
    Novembre 2004
    Messages
    54
    Détails du profil
    Informations personnelles :
    Âge : 34
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Novembre 2004
    Messages : 54
    Points : 49
    Points
    49
    Par défaut
    Merci, je ne m'attendais pas à ce que quelqu'un regarde mon code, je vais essayer de corriger ce passage.

    Au faite, pensez-vous que le C# était un bon choix pour un proxy cross-platform ?

  4. #4
    Expert éminent
    Avatar de smyley
    Profil pro
    Inscrit en
    Juin 2003
    Messages
    6 270
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2003
    Messages : 6 270
    Points : 8 344
    Points
    8 344
    Par défaut
    Ben je suppose que oui, après tout dès que ce n'est pas pour faire des drivers le C# (par extension, .NET) suffit dans la plupart des cas pour faire quelque chose de "bien".

  5. #5
    Membre du Club
    Profil pro
    Étudiant
    Inscrit en
    Novembre 2004
    Messages
    54
    Détails du profil
    Informations personnelles :
    Âge : 34
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Novembre 2004
    Messages : 54
    Points : 49
    Points
    49
    Par défaut
    Problème résolu, merci beaucoup.
    Je ferais plus attention aux boucles à l'avenir.

  6. #6
    Expert éminent
    Avatar de smyley
    Profil pro
    Inscrit en
    Juin 2003
    Messages
    6 270
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2003
    Messages : 6 270
    Points : 8 344
    Points
    8 344
    Par défaut
    n'oublie pas le

  7. #7
    Nouveau membre du Club
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2003
    Messages
    53
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2003
    Messages : 53
    Points : 37
    Points
    37
    Par défaut
    Citation Envoyé par smyley Voir le message
    Je pense que ça vient de là :

    Code c# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    while (true)
                {
                    if (socketClient.Available > 0)
                    {
                       ...
                    }
                    if (socketServer.Available > 0)
                    {
                        ...
                    }
                }
    Au final, si il n'y a rien d'Available, ce code est équivalent à
    Code c# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    while(true)
    {
    }
    Donc utilisation max du processeur. Essaye de mettre Thread.Sleep(1) ou Thread.Sleep(100) à la fin de ta boucle.

    ( Par contre, ton titre ne veux pas dire grand chose ... )

    Salut,

    Peux-tu m'expliquer stp pourquoi en mettant Thread.Sleep(1) ou Thread.Sleep(100) ca baisserait la conso du proc ? !!!

    Merci d'avance

  8. #8
    Nouveau membre du Club
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2003
    Messages
    53
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2003
    Messages : 53
    Points : 37
    Points
    37
    Par défaut
    Citation Envoyé par vincentweb Voir le message
    Problème résolu, merci beaucoup.
    Je ferais plus attention aux boucles à l'avenir.
    Salut,

    Tu peux expliquer stp comment t'as résolu ton problème...

  9. #9
    Membre éprouvé
    Profil pro
    Inscrit en
    Juin 2008
    Messages
    612
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Juin 2008
    Messages : 612
    Points : 1 050
    Points
    1 050
    Par défaut
    Salut
    -----

    Beau déterrage, LOL

    La boucle principale lit sans arrêt le socket, donc exécute du code perpétuellement même s'il n'y a rien à lire. Le programme n'est pas en "pause" en attendant l'arrivée d'un évènement, c'est une lecture "forcée"

    En ajoutant un sleep, ça permet 2 choses:

    1) Rendre la main immédiatement aux autres thread en attente, donc :
    - On lit le socket
    - On rend la main à d'autres threads
    - On relit le socket
    ...

    L'idéal étant quand même de n'appeler sleep que si on n'a effectivement rien lu.

    2) On ajoute une pause dans le thread concerné avant d'exécuter une autre lecture. Donc non seulement on rend la main aux autres threads, mais en plus on empêche de relire trop vite même s'il n'y a rien d'autre à exécuter

    A+
    Claude

  10. #10
    Nouveau membre du Club
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2003
    Messages
    53
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2003
    Messages : 53
    Points : 37
    Points
    37
    Par défaut
    Merci pour ta réponse rapide

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Programme qui consomme beaucoup de CPU
    Par houssine91 dans le forum Général Java
    Réponses: 4
    Dernier message: 16/03/2013, 15h18
  2. Réponses: 1
    Dernier message: 10/02/2010, 13h34
  3. Des astuces pour avoir une idée claire de ce qu'on veut ?
    Par Neolander dans le forum Méthodes
    Réponses: 8
    Dernier message: 17/03/2008, 08h53
  4. Réponses: 6
    Dernier message: 28/02/2008, 14h02
  5. programme qui consomme beaucoup de memoire
    Par gaut dans le forum Windows
    Réponses: 10
    Dernier message: 01/02/2005, 20h33

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo