One who cries out for that which is past - this is prayer in vain. How so? His wife is pregnant, and he says, "May it be Your will that my wife give birth to a male," - this is a prayer in vain.It would seem at first glance that this implies that the gender of the child is determined before a woman (or perhaps her husband) notices that she is pregnant. However, this seems not to be the case, for the Yerushalmi says:
The academy of Yanni say: The Mishnah was speaking about a woman on the birthing stool. But before that point, one may pray [for the gender] in accordance with "Behold, as clay in the hand of the potter...."This implies that the gender is not set until right before birth! And further, in Midrash Bereishis Rabba 72:6 we see the opinion of R' Yehudah ben Pazi who says that even on the birthing stool the fetus can be transformed, and thus one can still pray.
Most people today go by the rule that up to 40 days, one can pray for the gender, but not after that. [I have not yet found the source for this.]
According to modern science, the gender of the child is determined at conception (although I remember seeing something to the effect that there is a possibility of gender change at the very beginning of pregnancy, but I cannot recall where I read about it). This seems to contradict the gemara's interpretation of the Mishnah in Berachos.
However, it does not necessarily. There is a concept in the gemara that one should not count his grain too much, because then G-d will not cause a miracle and give him more. Meaning, that G-d does not want to do open miracles, but hidden ones He does. Therefore, if no one has detected the gender of the child, it would seem that G-d could perform a hidden miracle of changing the gender all the way through pregnancy. (However, today, with ultrasound, it would seem we cut this time down quite a bit - once we detect the gender, a gender change would be an open miracle). This would explain the Gemara's opinion of the Mishnah, that the prayer in vain refers to the time during birth, i.e. where the gender can be observed for the first time.
However, there is a source in Chazal that gender is determined at conception. The Midrash Tanchumah, Parashahs Pekudeh, sif 3 discusses what happens during conception and says that G-d tells a certain angel to go down and protect the droplet, and cultivate it into 365 parts. After doing so the angel shows the drop to G-d and says:
"I have done just as You have commanded me, so what has been decreed for this droplet?" The Holy One, Blessed is He, immediately decrees the destiny of the droplet; if it will be male or female, weak or strong, ...This Midrash is seemingly saying that the gender is decreed at conception! If this is the case, then perhaps (unless this goes against psak halachah) one could take this view and say that indeed gender is determined at conception, and explain the Mishnah above accordingly.